if, elif, else (Selection)
What is selection?
So far our programs ran every line from top to bottom (sequence). Real programs must choose: show "Pass" or "Fail", give a discount only above ₹1000, allow login only if the password matches. Choosing between paths based on a condition is called selection or decision making, and Python uses the keywords if, elif and else.
Indentation
Python uses indentation (spaces at the start of a line) to show which statements belong to a block. The line with if ends with a colon :, and the lines inside are indented by the same amount (usually 4 spaces). Other languages use { } for this.
if 10 > 5:
print('yes')Simple if
if condition:
statement(s) # run only when condition is Trueage = int(input('Enter your age: '))
if age >= 18:
print('You can vote.')
print('Thank you!') # not indented: always runsif-else
Exactly one of the two blocks runs.
n = int(input('Enter a number: '))
if n % 2 == 0:
print(n, 'is even')
else:
print(n, 'is odd')if-elif-else ladder
When there are many choices, use elif ("else if"). Python checks conditions top to bottom and runs only the first block whose condition is True.
marks = float(input('Enter percentage: '))
if marks >= 90:
grade = 'A'
elif marks >= 75:
grade = 'B'
elif marks >= 60:
grade = 'C'
elif marks >= 33:
grade = 'D'
else:
grade = 'E (needs improvement)'
print('Grade:', grade)If you write marks >= 33 first, every passing student gets grade D. Put the strictest condition first.
Nested if
An if inside another if is a nested if. Example: largest of three numbers.
a, b, c = 12, 45, 29
if a >= b:
if a >= c:
print('Largest is', a)
else:
print('Largest is', c)
else:
if b >= c:
print('Largest is', b)
else:
print('Largest is', c)The same can be written more simply with and: if a >= b and a >= c: … or just max(a, b, c).
Solved programs
1. Leap year
year = int(input('Enter year: '))
if year % 400 == 0:
print(year, 'is a leap year')
elif year % 100 == 0:
print(year, 'is not a leap year')
elif year % 4 == 0:
print(year, 'is a leap year')
else:
print(year, 'is not a leap year')2. Electricity bill with slabs
First 100 units ₹3/unit, next 100 units ₹5/unit, above 200 units ₹7/unit.
units = int(input('Units consumed: '))
if units <= 100:
bill = units * 3
elif units <= 200:
bill = 100 * 3 + (units - 100) * 5
else:
bill = 100 * 3 + 100 * 5 + (units - 200) * 7
print('Electricity bill = Rs.', bill)3. Menu-driven calculator
print('1. Add 2. Subtract 3. Multiply 4. Divide')
choice = int(input('Your choice: '))
x = float(input('First number: '))
y = float(input('Second number: '))
if choice == 1:
print('Result =', x + y)
elif choice == 2:
print('Result =', x - y)
elif choice == 3:
print('Result =', x * y)
elif choice == 4:
if y == 0:
print('Cannot divide by zero')
else:
print('Result =', x / y)
else:
print('Invalid choice')One-line if (conditional expression)
temp = 31 status = 'Hot' if temp > 30 else 'Pleasant' # one-line if-else print(status)
Summary & practice
ifruns a block when the condition is True;elsewhen it is False.elifchecks many conditions; only the first true block runs.- Colon
:at the end and consistent indentation are compulsory. - Nested if = if inside if.
Write programs to: (1) check whether a character is a vowel, (2) find the absolute value of a number without abs(), (3) give 10% discount if the bill is above ₹2000, otherwise 5%.
Hint: (1) if ch.lower() in 'aeiou': (2) if n < 0: n = -n
