Jump to content

Truth and flow control in Python

From IdeaWazaWiki
Revision as of 15:37, 24 February 2007 by 152.43.1.4 (talk) (First couple sections)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Boolean Expressions

Python has a Boolean type. The two values for this type are True and False. Note the capitalization: the first letter must be capitalized. Most text editors, including IDLE, will highlight True and False when properly capitalized.

The bool() Function

If you need to convert something into a boolean value, use the bool() function. For example:

>>> bool(1)
True
>>> bool(0)
False
>>> bool(500)
True
>>> bool(-1)
True

In Python, the integer 0 evaluates to False. All other integers will evaluate to True. As a general rule, try to avoid using Floating Point numbers in boolean expressions: use the int() operator to turn them into integers first.

Strings behave similarly: an empty string evalueates to False, all other strings evaluate to True.

>>> bool("Hello World!")
True
>>> bool("")
False
>>> bool("True")
True
>>> bool("False")
True
>>> bool("0")
True

Note that what is in the string does not matter: It can be "0", "False" or "ReallyReallyFalse": Everything that is not simply an empty string will evaluate to true.

Comparison Operators