Reputation: 13
I recently encountered an example of an if-else conditional statement and could not understand the rationale behind its output. The following are the statements:
if 0:
1
else:
2
Output: 2
I tried different integers in 0's place, and received 1 each time. Is this because the zero in the if condition represents False? But then why do integers other than 1 still satisfy the if condition?
Thanks!
Edit: Thank you for all your answers. I now understand that any integer except 0 in the 'if' statement will make the statement True by default, resulting in an output of 1, in this case.
Upvotes: 1
Views: 429
Reputation: 51008
Python will always attempt to determine the "truthiness" of a given value used in a boolean context. In Python any numerical value of 0 (or 0.0) is considered false, and string, dictionary, list, or other iterable (or other class that can report its length) is false if it's empty or has length of 0. Also, None
and boolean False
are considered false.
Other values are considered true.
More details: https://docs.python.org/2.4/lib/truth.html.
Upvotes: 2
Reputation: 5714
1 is considered True
while 0 is False
,just like in binary.
Any non-zero numeric value is evaluated as True in a conditional statement.
bool type is just a subtype of int in Python, with 1 == True
and 0 == False
.
Upvotes: 0
Reputation:
In Python, bool
is a subtype of int
. False has the value 0, while other non-zero integers have the subtype bool
with the value True
.
To see this for yourself try this: False == 0
And to see the subtypes of int try this: int.__subclasses__()
Upvotes: 0