Day 9: making decisions in code. The if statement lets us run or skip a block of code based on a condition.
Basic if / else
raining = False
if raining == True:
print("Take Umbrella")
else:
print("No need for Umbrella")
Watch the difference: = assigns a value, == compares.
elif (else if)
age = 16
parent_came = True
if age >= 18:
print("Unrestricted")
elif parent_came == True:
print("allowed")
else:
print("Not Allowed")
A real-life example, grades:
mark = 89
if mark >= 90:
print("A+ Grade")
elif mark >= 75:
print("A Grade")
elif mark >= 60:
print("B Grade")
elif mark >= 35:
print("C Grade")
else:
print("Re Appear")
Output: A Grade. Python checks from top to bottom and stops at the first condition that's true.
We also did a simplified electricity bill with slab rates (units ≤100 free, ≤400 at 4.70, and so on). Same idea, just more elifs.
Nested if
physical_test = True
written_test = True
if physical_test == True:
if written_test == True:
print("Send them appointment order")
else:
print("Physical Test Pass, Written Test - Fail")
else:
print("Physical Test - Not Clear")
Tricky ones from class (guess before you scroll!)
name3 = " "
if name3:
print("Welcome")
else:
print("Vanakkam")
→ Welcome. A space is still a character, so the string isn't empty. Only "" is falsy.
if 'prem' == 'Prem':
print("Hi Prem")
else:
print("Hello Prem")
→ Hello Prem. Comparisons are case-sensitive.
result = True
if result == 1:
print("One")
elif result == True:
print("True")
→ One. True == 1 in Python!
a, b = False, True
if a and b:
print("Hi")
elif a or b:
print("Hello")
→ Hello. Think of and like multiplying (0 × 1 = 0) and or like adding (0 + 1 = 1).
The trainer's advice I'm keeping: practise both easy and hard programs. Skipping either one is a mistake.
Top comments (0)