Reputation: 19
x = 0
if not x:
print(bool(x))
print("Evaluated True")
else:
print(bool(x))
print("Evaluated False")
Output
False
Evaluated True
Why is the else block not executed?
I think x = 0 is False
, not x is True
. Or do I misunderstand the boolean definition?
Upvotes: 0
Views: 334
Reputation: 177
False
Evaluated True
Your output is correct. You got the boolean concept right(x = 0 is False, not x is True) but your implementation is wrong.
x = 0
if not x:
print(bool(x))
print("Evaluated True")
In your code:
if not x
means if (not x)==True
which is absolutely correct hence the if condition runs.
Using if (some condition)
is sometimes tricky. Its also sometimes due to absence of parentheses.
You can achieve the desired output with this if (not x)==False
.
Upvotes: 1
Reputation: 2313
The boolean value is true for all except 0. not x == True
so it's evaluated true
.
Upvotes: 1
Reputation: 1328
>>> x = 0
>>> if x:
... print(bool(x), "Evaluated True")
... else:
... print(bool(x),"Evaluated False")
...
False Evaluated False
Note: The boolean value is True for all integers except 0
Upvotes: 2
Reputation: 417
if not x
This is true, that's why the line following the if is executed. Ergo, the else is NOT executed. It would only be executed if the if statement would be false.
Upvotes: 1
Reputation: 1410
You must print your if expression 'not x'. Then you see not x == not False == True.
x = 0
if not x:
print(bool(not x))
print("Evaluated True")
else:
print(bool(not x))
print("Evaluated False")
answer:
True
Evaluated True
Upvotes: 2
Reputation: 188
Thus it as you say: not x == True
so the if statement get executed.
Upvotes: 1
Reputation: 546
When the expression inside the if statement is true the if block is executed. Since x is 0 then not x
is true which means the if block will execute not the else block.
print(bool(x)) will print false since x is 0.
Upvotes: 1