Python Fundamentals Tutorial : Simple Expressions

4. Simple Expressions

4.1. Boolean Evaluation

Boolean expressions are created with the keywords and, or, not and is. For example:

>>> True and False
False
>>> True or False
True
>>> not True
False
>>> not False
True
>>> True is True
True
>>> True is False
False
>>> 'a' is 'a'
True

Compound boolean evaluations shortcut and return the last expression evaluated. In other words:

>>> False and 'a' or 'b'
'b'
>>> True and 'a' or 'b'
'a'

Up until Python 2.6, this mechanism was the simplest way to implement a "ternary if" (a = expression ? if_true : if_false) statement. As of Python 2.6, it is also possible to use:

>>> 'a' if True else 'b'
'a'
>>> 'a' if False else 'b'
'b'

4.2. Truthiness

Many of the types in Python have truth values that can be used implicitly in boolean checks. However, it is important to note that this behavior is different from C where almost everything ends up actually being a zero. True, False and None in Python are all singleton objects and comparisons are best done with the is keyword.

Table 1. Truthiness values

Value

truthy

None

True

False

None

N

Y

N

N

0

N

N

N

N

1

Y

N

N

N

'hi'

Y

N

N

N

True

Y

N

Y

N

False

N

N

N

Y

[]

N

N

N

N

[0]

Y

N

N

N



4.3. Branching (if / elif / else)

Python provides the if statement to allow branching based on conditions. Multiple elif checks can also be performed followed by an optional else clause. The if statement can be used with any evaluation of truthiness.

>>> i = 3
>>> if i < 3:
...     print 'less than 3'
... elif i < 5:
...     print 'less than 5'
... else:
...     print '5 or more'
...
less than 5

4.4. Block Structure and Whitespace

The code that is executed when a specific condition is met is defined in a "block." In Python, the block structure is signalled by changes in indentation. Each line of code in a certain block level must be indented equally and indented more than the surrounding scope. The standard (defined in PEP-8) is to use 4 spaces for each level of block indentation. Statements preceding blocks generally end with a colon (:).

Because there are no semi-colons or other end-of-line indicators in Python, breaking lines of code requires either a continuation character (\ as the last char) or for the break to occur inside an unfinished structure (such as open parentheses).

4.5. Lab

Edit hello.py as follows:

from datetime import datetime

hour = datetime.now().hour
if hour < 12:
    time_of_day = 'morning'
else:
    time_of_day = 'afternoon'

print 'Good %s, world!' % time_of_day

4.6. Multiple Cases

Python does not have a switch or case statement. Generally, multiple cases are handled with an if-elif-else structure and you can use as many elif?s as you need.

4.7. Lab

Fix hello.py to handle evening and the midnight case.