If…Else
marks = 72
if marks >= 80:
print("A+")
elif marks >= 50:
print("Pass")
else:
print("Try again")Python checks the conditions from top to bottom.
1Level 1 · BasicsBasics
Real programs make decisions: show "Pass" or "Fail", let a user in or not, charge a discount or not. if, elif and else let your program choose what to do.
The if statement
marks = 75
if marks >= 40:
print("You passed!")
print("Done")
Three things to notice:
- The condition (
marks >= 40) is followed by a colon. - The lines that belong to the
ifare indented by 4 spaces. That indented group is called a block. - The block runs only when the condition is
True.print("Done")isn't indented, so it always runs.
else: the other way
if marks >= 40:
print("Pass")
else:
print("Fail")
elif: more than two choices
elif means "else if". Python checks the conditions from top to bottom and runs the first block whose condition is True, then skips the rest:
if marks >= 80:
grade = "A+"
elif marks >= 70:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "F"
Order matters. If you checked marks >= 60 first, a mark of 85 would get a B!
Combining conditions
Use and, or and not from the Operators lesson: if age >= 18 and has_id:. You can also put an if inside another if (nesting), but combined conditions are often easier to read.
One-line choice
For simple either/or values there's the conditional expression: status = "even" if n % 2 == 0 else "odd".
Key points: end each condition with a colon; indent the block; elif chains stop at the first True condition; else catches everything left.
See it in actionPython picks one branch
Watch which lines the arrow visits: the other branches are skipped.
Try it yourselfExample 1: Pass or fail
Change marks to 30 and run again.
Output appears herePass mark
The pass mark is 40. Fill the blanks so a score of 55 prints Pass.
score = 55 if score 40: print("Pass") : print("Fail")
Example 2: Grades with elif
Only the first matching branch runs. Try 95, 65 and 20.
Output appears hereMissing pieces
This should print Cold for 12 degrees, but Python reports an error. Fix it.
Grade ladder
Fill the blanks so a mark of 72 prints B.
mark = 72 if mark >= 80: print("A") mark >= 60: print("B") : print("C")
Example 3: Decisions from user input
Change the number in the Input box.
Output appears hereThe bigger number
Read two whole numbers (one per line) and print the bigger one. If they are equal, print Equal. Don't use max().
Example input4
9Expected output9
Example 4: Combining conditions
A ticket is free for children under 5 and seniors 60 or over.
Output appears hereLeap year
Read a year and print Leap or Not leap. A year is a leap year if it divides by 4, except years that divide by 100 unless they also divide by 400.
Example input2024Expected outputLeap
2Level 2 · IntermediateNested decisions and cleaner conditions
Nested if
An if inside another if handles decisions that depend on earlier ones, like "is it a leap year?": divisible by 4, but not by 100, unless also by 400.
Truthiness in conditions
Empty things and zero are false: if name: means "if name is not empty", and if not name: means "if name is empty". You rarely need == True or len(name) > 0.
Guard clauses
Check the bad cases first and stop early. This keeps the main logic un-indented and easy to read.
in instead of many or
if letter in "aeiou": is clearer than letter == "a" or letter == "e" or ....
See it in actionThe leap year decision tree
Watch which branches the arrow enters for 1900. Then try 2000 and 2024 in the editor below.
Example 5: The same rule in one line
Combined conditions can replace nesting. Try 2000, 2023 and 2024 and check the answers match the decision tree above.
Output appears hereExample 6: Guard clauses and truthiness
Try name = "", then age = -3, then age = 3, then day = "Tue". The bad cases are checked first, so the price logic only runs for good input.
Output appears here3Level 3 · Advancedmatch-case and the order of branches
Structural pattern matching
Since Python 3.10, match compares a value against patterns. It can match literal values, several at once (case "q" | "quit":), and add a guard (case n if n < 0:). case _: catches everything else. (Once you know lists, match can even check their shape.)
Order matters in a chain
Python takes the first branch whose condition is true and skips the rest. For grade bands, test the highest band first; if you test mark >= 33 first, an 85 would get a D.
Bands with chained comparisons
When branches can't be ordered, give each one both limits: 70 <= mark < 80. Then the order no longer matters.
Example 7: A tiny command interpreter with match
Change command to "n", "look", "dance" or "exit". Then add a "jump" command.
Output appears hereExample 8: Grades with match and guards
The highest band is tested first, so the first true guard wins. Try 95, 52, 33 and 12.
Output appears hereif x > 3, or mixing tabs and spaces, gives a SyntaxError or IndentationError. Also, if x = 5: is wrong: use == to compare.What does this print?
x = 15
if x > 10:
print("big", end=" ")
if x > 5:
print("medium")50 graded problems are waiting in Topic Practice.