[Tutor] Question about the use of None
dyoo at hkn.eecs.berkeley.edu
Fri Jun 11 19:47:44 EDT 2004
On Fri, 11 Jun 2004, [iso-8859-1] Wilfred Y wrote:
> Hi,I came across this keyword None. The document I read says "None is
> python's way of representing nothing. It evaluates to False when treated
> as a condition"
Which document are you referring to? We can also take a look and see if
the wording is weird. What you're describing right now actually sounds
subtly off. *grin*
The 'None' value is a single value that's used to represent the idea of
nothing. It can be used in comparisons:
>>> None == 1
>>> None == 0
>>> None == ""
>>> None == None
and the only 'value' that None compares favorably to is itself the None
> So I assume, if I do start=None, then it's as good as saying start="" or
> start=0Now, the code to represent it's use is pretty confusing. It goes
> like this:start=Nonewhile start != "" start=raw_input("Press enter to
> exit, or key in a string: ")The confusing part is here, since start =
> "", then it should never be able to go into the while loop.
[Small note: use indentation to set off your code from your explanation;
it'll make it easier for us to test and see how your code works.]
Let's look at the code again:
start = None
while start != "":
start = raw_input("Press enter to exit, or key in a string: " )
> So it seems None does have a value, which explains why it managed to
> enter the while loop.
Yes. None is a perfectly legitimate value.
What the author of the material you were reading was trying to say,
though, is that None is one of the values that Python considers as a
'false' value. If we are working with an 'if' statement, like:
then the '...' part gets executed only if 'foo' is a true-ish value.
Every value in Python is considered true, except for a few special cases.
You may find the following useful:
>>> def testTruth(value):
... """Prints true or false, depending if the value that we get is
... a true or false value."""
... if value:
... print "True!"
... print "False!"
The function above will say "True!" or "False!", depending if the value we
pass is considered True or False to the 'if' statement.
Try testTruth() on these values:
42 - 2 * 21
0 == 0
If you can predict when it says True! or False! with good accuracy, then
you probably understand the author's point. *grin*
Python is actually quite loose when it comes to truth and falsehood. In
fact, there are other computer languages that are really strict about this
More information about the Tutor