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> else: <code block>
<condition>: sentence that can be evaluated as true or false.
<code block>: sequence of command lines.
elseare optional and several
ifmay be used but only one
elseat the end.
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' else: 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>
<value 1> if
<condition> is true and
<value 2> otherwise.