26 min read
elif and Nested if
Choose between several options with elif, and put an if inside another if — the grade and cinema ticket programs.
elif: Several Choices
elif means "else if". Python checks each condition in order and runs the first block whose condition is True, then skips the rest.
Grades: a chain of decisions
Read this flowchart as text
- Terminator: Start (then → INPUT mark)
- Input/output: INPUT mark (then → mark >= 75?)
- Decision: mark >= 75? (Yes → grade = "A"; No → mark >= 65?)
- Process: grade = "A" (then → OUTPUT grade)
- Decision: mark >= 65? (Yes → grade = "B"; No → mark >= 50?)
- Process: grade = "B" (then → OUTPUT grade)
- Decision: mark >= 50? (Yes → grade = "C"; No → mark >= 35?)
- Process: grade = "C" (then → OUTPUT grade)
- Decision: mark >= 35? (Yes → grade = "S"; No → grade = "W")
- Process: grade = "S" (then → OUTPUT grade)
- Process: grade = "W" (then → OUTPUT grade)
- Input/output: OUTPUT grade (then → Stop)
- Terminator: Stop
grade.pyPython
mark = int(input("Mark: ")) if mark >= 75: grade = "A"elif mark >= 65: grade = "B"elif mark >= 50: grade = "C"elif mark >= 35: grade = "S"else: grade = "W" print("Grade:", grade)Expected output
Mark: 68 Grade: B
Nested if: The Cinema Ticket
A nested if is an if inside another if's block. Dinesh writes the Starlight Cinema ticket program from his flowchart:
The cinema flowchart
Read this flowchart as text
- Terminator: Start (then → INPUT age)
- Input/output: INPUT age (then → age < 12?)
- Decision: age < 12? (Yes → price = 600; No → age >= 60?)
- Process: price = 600 (then → OUTPUT price)
- Decision: age >= 60? (Yes → price = 800; No → price = 1200)
- Process: price = 800 (then → OUTPUT price)
- Process: price = 1200 (then → OUTPUT price)
- Input/output: OUTPUT price (then → Stop)
- Terminator: Stop
cinema.py — nested ifPython
age = int(input("Age: ")) if age < 12: price = 600else: if age >= 60: price = 800 else: price = 1200 print(f"Ticket price: LKR {price}")Expected output
Age: 65 Ticket price: LKR 800
The inner if…else is indented twice, because it sits inside the else block. The same logic can be written flatter with elif:
cinema.py — with the Tuesday discountPython
age = int(input("Age: "))day = input("Day: ") if age < 12: price = 600elif age >= 60: price = 800else: price = 1200 if day == "Tuesday": price = price - 200 print(f"Ticket price: LKR {price}")Expected output
Age: 30 Day: Tuesday Ticket price: LKR 1000
| Test plan for cinema.py | |||
|---|---|---|---|
More lessons in Python Programming · Next: for Loops and range() · Previous: if and else
