Lesson 04
if..elif..else Statement — Multi-Way Decisions
Master Python if-elif-else chains for digit names, biggest-of-three logic, and dictionary-based classification with clear multi-way branching.
Beginner30 min
if..elif..else statement
Use elif (else-if) to chain mutually exclusive conditions. Python checks top to bottom and runs the first matching block only.
Syntax
if condition_1:
block_1
elif condition_2:
block_2
elif condition_3:
block_3
else:
default_blockThe else at the end is optional — it runs when no condition matched.
Example 1 — Digit name (elif chain)
d = int(input("Enter a Digit:"))
if d == 0:
print("{} is ZERO".format(d))
elif d == 1:
print("{} is ONE".format(d))
elif d == 2:
print("{} is TWO".format(d))
elif d == 3:
print("{} is THREE".format(d))
elif d == 4:
print("{} is FOUR".format(d))
elif d == 5:
print("{} is FIVE".format(d))
elif d == 6:
print("{} is SIX".format(d))
elif d == 7:
print("{} is SEVEN".format(d))
elif d == 8:
print("{} is EIGHT".format(d))
elif d == 9:
print("{} is NINE".format(d))
elif d < 0 and d in [-1, -2, -3, -4, -5, -6, -7, -8, -9]:
print("{} is negative digit".format(d))
elif d < 0 and d not in [-1, -2, -3, -4, -5, -6, -7, -8, -9]:
print("{} is negative number".format(d))
else:
print("{} is positive number".format(d))Example 2 — Biggest of three numbers
a = float(input("Enter Value of a:"))
b = float(input("Enter Value of b:"))
c = float(input("Enter Value of c:"))
if (a >= b) and (a > c):
print("Big({},{},{})={}".format(a, b, c, a))
elif (b > a) and (b >= c):
print("big({},{},{})={}".format(a, b, c, b))
elif (c >= a) and (c > b):
print("big({},{},{})={}".format(a, b, c, c))
elif (a == b) and (b == c) and (a == c):
print("All Values are equal")Example 3 — Dictionary lookup with ternary
dobj = {
0: "ZERO", 1: "ONE", 2: "TWO", 3: "THREE", 4: "FOUR",
5: "FIVE", 6: "SIX", 7: "SEVEN", 8: "EIGHT", 9: "NINE",
-1: "-ONE", -2: "-TWO", -3: "-THREE", -4: "-FOUR", -5: "-FIVE",
-6: "-SIX", -7: "-SEVEN", -8: "-EIGHT", -9: "-NINE",
}
d = int(input("Enter a Digit:"))
res = dobj.get(d) if dobj.get(d) != None else "+VE Number" if d > 0 else "-VE Number"
print("{} is {}".format(d, res))Example 4 — Employee pay slip (nested if..else)
Salary slabs use nested if..else inside validation:
eno = int(input("Enter Employee Number:"))
ename = input("Enter Employee Name:")
bsal = float(input("Enter Employee Basic Salary:"))
if bsal <= 0:
print("{} is invalid Salary".format(bsal))
else:
if bsal >= 10000:
da = (25 / 100) * bsal
ta = (15 / 100) * bsal
# ... higher slab allowances and deductions ...
else:
da = (12.5 / 100) * bsal
ta = (7.5 / 100) * bsal
# ... lower slab allowances and deductions ...
netsal = (bsal + da + cca + ta + hra + ma) - (lic + gpf)
print("NET SALARY:{}".format(netsal))
print("Program Execution Completed")Knowledge check
Q1: How many elif blocks can run in one chain?
Answer: At most one — the first match wins.
Loading playground…