简体   繁体   中英

Can't understand the reason for an output in Python

I've just started learning Python. I came across following code

if 0:

  print "And now for something completely different..." 

else:

  print "What's all this, then?" 

I understand that output should be What's all this, then? but I can't seem to find a proper explanation for that. Hope someone can make me understand that.

Thanks.

0 is False in a boolean context. Same applies for empty string, lists, etc.

From the python docs :

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)

在Python(和许多其他编程语言)中,零被解释为“假”。

0 is False. Both boolean and logically and in just about every other case.

What are you confused about?

Numeric zero is always interpreted as false in Python:

http://docs.python.org/reference/expressions.html#booleans

And almost anything that isn't 0 is True when used in a test. Any number (including negatives) is treated as True, but 'None' is False. Non-empty character strings are True, empty ones are False.

Check out boolean or logical functions of Python in the docs. Also, forget everything you ever learnt in basic math(s) at school, because....

>>> 1 and 1
1

>>> 2 and 2
2

Honestly, that makes sense...

As stated elsewhere, unlike some languages (but like some others), Python will interpret 0 as false, thus the else is activated instead of the then. To make the then section run, you'd have to do something like if 1: (or another non-zero value) instead. Please don't code like this in real life. For more, please see the Python docs on if (and another ) and booleans .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM