Lesson 03
if..else Statement — Two-Way Branching
Write Python if-else statements for mutually exclusive decisions: biggest of two numbers, digit names, and ticket validation patterns.
Beginner22 min
if..else statement
When only one branch should run, use if..else. The else block runs when the if condition is false.
Syntax
if test_condition:
block_when_true
else:
block_when_falseYou can nest if..else inside else for multi-level decisions (before elif was introduced, this was the standard approach).
Example 1 — Biggest of two with nested else
a = float(input("Enter First Value:"))
b = float(input("Enter Second Value:"))
if a > b:
print("big({},{})={}".format(a, b, a))
else:
if b > a:
print("big({},{})={}".format(a, b, b))
else:
print("Both Values equal")
print("Program execution completed")Example 2 — Movie ticket validation
tkt = input("Do u have ticket(yes/no):")
if tkt.lower() == "yes":
print("Enter into theater")
print("watch the Moviee")
print("Eat pop corn!!!")
if tkt.lower() not in ["yes", "no"]:
print("Plz Learn Typing")
print("Goto Home and Read Python Notes")Note: Invalid input (
not in ["yes", "no"]) is handled with a separate simpleif— both checks can be relevant in one program.
Example 3 — Digit name with nested if..else
Deeply nested if..else works but gets hard to read. Compare with the cleaner if..elif..else version in the next lesson.
d = int(input("Enter a Digit:"))
if d == 0:
print("{} is ZERO".format(d))
else:
if d == 1:
print("{} is ONE".format(d))
else:
if d == 2:
print("{} is TWO".format(d))
# ... continues for each digit ...
else:
print("{} is NUMBER".format(d))if..else vs simple if
| Pattern | Use when |
|---|---|
Multiple simple if |
Several conditions may all be true |
if..else |
Exactly two paths (or nested paths) |
Knowledge check
Q1: When does the else block run?
Answer: When the if condition is false.
Next: File 04 — if..elif..else
Loading playground…