Python for Developers

First edition

Chapter 3: Control Flow

It is very common for a program that certain sets of instructions are executed conditionally, in cases such as validating data entries, for example.


if <condition>:
    <code block>
elif <condition>:
    <code block>
elif <condition>:
    <code block>
    <code block>


  • <condition>: sentence that can be evaluated as true or false.
  • <code block>: sequence of command lines.
  • The clauses elif and else are optional and  several elifs for the if may be used but only  one else at the end.
  • Parentheses are only required to avoid ambiguity. Example:
In [3]:
temp = 23 # temperature value used to test

if temp < 0:
    print 'Freezing...'
elif 0 <= temp <= 20:
    print 'Cold'
elif 21 <= temp <= 25:
    print 'Normal'
elif 26 <= temp <= 35:
    print 'Hot'
    print 'Very Hot!'

Imagine that in the above program, 23 is the temperature which was read by  some sensor or manually entered by the user and Normal is the response of the program.

If the code block is composed of only one line, it can be written after the colon:

if temp < 0: print 'Freezing...'

Since version 2.5, Python supports the expression:

<variable> = <value 1> if <condition> else <value 2>

Where <variable> receives <value 1> if <condition> is true and <value 2> otherwise.

In [1]: