Our learning goals are understanding the structure and flow of if and else, writing programs that branch on conditions, and performing correct type conversion before comparisons while keeping conditions clear.
The power of programs lies in doing different things based on conditions. In Python, we use if to test whether an expression is True; if it is, the indented block under if runs; otherwise, the block under else runs. Mind the colon and indentation—they define the block. Conditions typically use comparison operators (like >=, ==). When comparing numbers, remember to convert input() results to int or float first.
Example A: Pass or Fail
score = int(input("Enter your score: "))
if score >= 60:
print("Pass")
else:
print("Fail")
Notes: Convert input to int before comparing with 60; otherwise string–number comparison is invalid.
Example B: Ticket Price (Child Free)
age = int(input("Enter your age: "))
if age < 6:
print("Free ticket")
else:
print("Ticket: $10")
Key ideas: Choose outputs/values based on condition; a if cond else b is a conditional expression.
Example C: String & Case
word = input("Type YES or NO: ")
if word.lower() == "yes":
print("You chose YES")
else:
print("You did not choose YES")
Notes: String comparison is case-sensitive; normalize with .lower() or .upper() before comparing.
Common Pitfalls:
= assigns, == compares; if x = 5: is invalid, use if x == 5:Convert input strings with int()/float() before numeric comparisons
if condition with a colon; indent consistently (4 spaces)Progressive Practice:
Exercise A: Read an integer; print Even if it’s even, else Odd.
Answer example A:
n = int(input("Enter an integer: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")
Exercise B: Read temperature t (°C). If t >= 30, print Hot, else print OK; extension: if t < 10, print Cold
Answer example B:
t = float(input("Temperature (°C): "))
if t >= 30:
print("Hot")
else:
print("OK")
Now our programs can ‘choose’ with if/else. Next, when there are more than two cases, we’ll add elif for multi-branch decisions. Let’s move on!