It is very common for a program that certain sets of instructions are executed conditionally, in cases such as validating data entries, for example.
Syntax:
if <condition>:
<code block>
elif <condition>:
<code block>
elif <condition>:
<code block>
else:
<code block>
Where:
<condition>: sentence that can be evaluated as true or false.<code block>: sequence of command lines.elif and else are optional and several elifs for the if may be used but only one else at the end.
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'
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>
Where <variable> receives <value 1> if <condition> is true and <value 2> otherwise.
In [6]:
temp = 27
if temp < 0:
print("Freezing")
elif 0 <= temp < 13:
print("Cold")
elif 13 <= temp and temp < 29:
print("Normal")
else:
print("Hot")
In [8]:
temp = 27
ans = "Normal" if 10<temp<27 else "Uncomfortable"
print(ans)
In [ ]:
In [ ]: