Prev: - 'while' loop       |       Next: Break, continue, pass

# 'If' control¶

## if¶

• The 'if' command evaluates the truth value of a conditional expression (or 'condition') and changes the program flow depending on the value of the condition (True or False)
• The general form of the Python 'if' command is as follows:
In [ ]:
if condition-1:
block-1
elif condition-2:
block-2
...........................
elif condition-N:
block-N
else:
block_else

• If condition-1 is True then block-1 is executed (and the if command is exited)
• If, however, condition-1 is False then the conditions in the elif conditions are tested. If one of them is True then the respective block is executed (and the if structure command is exited)
• If no elif exists or all elif conditions are False then the 'else' block is executed

## Simple 'if' examples¶

In [1]:
# Python allows concise forms of composite conditions
x = int(input())
if 0 < x < 10:          # instead of:  0<x and x<10
print('x in the (0,10) interval')
else:
print('x out of the (0,10) interval')

5
x in the (0,10) interval

In [2]:
# When implementing multiple if branches: use elif - avoid if-else nesting

if 18.5 <= grade <= 20:
perform = 'Excellent'
elif 15 <= grade < 18.5:
perform = 'Very Good'
elif 12.5 <= grade < 15:
perform = 'Good'
elif 10 <= grade < 12.5:
perform = 'Accept'
else:
perform = 'Fail'

print(perform)

15
Very Good

In [3]:
import random

a = random.randint(1,3)

if a == 2:
print('Equal')
elif a < 2:
print('Less than 2')
else:
print('Greater than 2')

print('End of if control, a =',a)

Less than 2
End of if control, a = 1

In [4]:
# Note the use of docstring enclosed in triple quotes
1. spam
2. chorizo
3. salchichón
4. jamon iberico de belotta
'''

if c=='1':
print('spam: €0.25')
elif c=='2':
print('chorizo: €2.45')
elif c=='3':
print('salchichón = €1.99')
elif c=='4':
print('jamon iberico de belotta = €100.10')
else:


Please make a choice:
1. spam
2. chorizo
3. salchichón
4. jamon iberico de belotta

spam: €0.25


## Conditional expression¶

• Python has also conditional expressions in the form:
  "True_expression if Condition else False_expression"
In [5]:
x=False
a=1 if x else 2
a

Out[5]:
2
In [6]:
a = 'Alpha'
b='1'
print(a) if b else 'X'

Alpha

• Conditional expressions will be very useful in constructing lists with the list comprehension method as we shall see later on

. Free learning material
. See full copyright and disclaimer notice