Python lesson 4
Making Decisions with If Statements
Teach Python to choose different paths. Like a Choose-Your-Own-Adventure story!
How Python Makes Decisions
If statements let your code choose what to do based on a condition. Is the age over 13? Take one path. Is it not? Take another. Python checks the condition and picks the right path!
if age >= 13:
print("Teen!") # runs when TRUE
else:
print("Kid!") # runs when FALSE
age = 15
if age >= 13:
print("Teen!")
else:
print("Kid!")
Which Path Does It Take?
age = 10
if age >= 13:
print("Teen")
elif age >= 8:
print("Kid")
else:
print("Little")
If and Else
Click Run to see if/else in action. Then try changing age = 15 to age = 8 and click Run again!
Hint: Click Run first. Then change 15 to 8 and run again. Python picks the other message!
age = 15
if age >= 13:
print("Teen!")
else:
print("Kid!")
Three Choices with elif
Run this code. Then try changing temp to 30, then to 5. Does Python pick the right message each time?
Hint: Try temp = 30 for Hot day, temp = 20 for Nice day, temp = 5 for Cold day.
temp = 20
if temp > 25:
print("Hot day!")
elif temp > 15:
print("Nice day!")
else:
print("Cold day!")
Secret Password Checker
Run the code. Then change the password to something wrong. What happens? Change it back to see it work!
Hint: Change "python123" to any other word and see the else branch run!
password = "python123"
if password == "python123":
print("Access granted!")
else:
print("Wrong password!")
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.