Lesson 5 of 14 · about 14 minutes · if, else, elif and comparisons.
⚡ 0 XP
Step 1 of 2
if and else
if lets your program choose. It checks a condition that is either True or False:
== equal, != not equal
<, >, <=, >=
The line ends with a colon :, and the code that belongs to it is indented by 4 spaces. That indent is how Python knows which lines are inside the if. else: runs when the condition is False.
Careful: = stores a value, == compares two values.
Example
marks = int(input("Marks: "))
if marks >= 33:
print("Pass 🎉")
else:
print("Try again next time")
🎯 Challenge: Can I vote? +15 XP
In India you can vote at 18. Read the age. If it is 18 or more, print You can vote!. Otherwise print how long to wait, e.g. Wait 3 more years for age 15.
Try twice to unlock the solution (0/2)
main.pyCtrl ⏎
Output
What your program prints appears here.
Checklist
Press Run to check your code.
○
20 can vote
○
18 can vote too
○
15 waits 3 more years
Lesson notes (text version)
1. if and else
if lets your program choose. It checks a condition that is either True or False:
== equal, != not equal
<, >, <=, >=
The line ends with a colon :, and the code that belongs to it is indented by 4 spaces. That indent is how Python knows which lines are inside the if. else: runs when the condition is False.
Careful: = stores a value, == compares two values.
marks = int(input("Marks: "))
if marks >= 33:
print("Pass 🎉")
else:
print("Try again next time")
Challenge: Can I vote?
In India you can vote at 18. Read the age. If it is 18 or more, print You can vote!. Otherwise print how long to wait, e.g. Wait 3 more years for age 15.
2. elif: more than two choices
When there are more than two cases, chain them with elif ("else if"). Python checks from the top and runs only the first branch whose condition is True, then skips the rest.
So the order matters. In the example, a score of 95 matches >= 90 first and never reaches the >= 60 check.