user1592380
user1592380

Reputation: 36227

Object has value but does not appear to exist?

I have the following Python code:

if bedrooms: # bedrooms exists
    .....
else: #  BEDROOMS DOES NOT EXIST 
    bn = "BEDROOMS DOES NOT EXIST"

I was stepping through it in my debugger and noticed that even though bedroom == 0 , the flow jumps to the else statement.

To test this I tried:

>>> bedrooms
0.0
>>> type(bedrooms)
<type 'float'>

Can someone explain what is going on here?

Upvotes: 1

Views: 95

Answers (1)

user2555451
user2555451

Reputation:

0 always evaluates to False in Python:

>>> bool(0)
False
>>> bool(0.0)
False
>>> not 0
True
>>>

Consequentially, doing this:

if 0:
    ...
else:
    ...

will always cause the else block to be executed.

For a complete list of what evaluates to False, see Truth Value Testing in the Python docs.


If you want to check if bedrooms is defined, then you could use a try/except block and catch for a NameError (which is raised when you use a nonexistent name):

try:
    bedrooms
except NameError:
    # bedrooms is not defined

But this begs the question of why you need to do this in the first place. If it involves dynamic variable names, then I would like to say that those are considered a bad practice by most Python programmers and should be avoided. They can quickly lead to maintenance problems and it is very easy to lose track of the names that were created.

Upvotes: 6

Related Questions