How if / else works
Python evaluates the condition after if. If it is True, the indented block runs. Otherwise the else block runs. Only one of the two paths is ever taken.
marks = 72
if marks >= 50:
print("Pass")
else:
print("Fail")Output: Pass, because 72 >= 50 is TRUE.
Adding more choices with elif
if marks >= 80:
print("A")
elif marks >= 60:
print("B")
else:
print("C")Python checks each condition from top to bottom and stops at the first TRUE one.
Common beginner mistakes
- Using
=(assignment) instead of==(comparison). - Forgetting the colon
:after the condition orelse. - Mixing indentation, so the wrong lines belong to a block.
Practice exercises
Try each one yourself first, then open it in the Visualizer to watch every line run.
Exercise 1
Pass or fail
Print "Pass" when marks are 50 or more, otherwise "Fail".
marks = 43
# your if / else hereHint
Use >= to include 50 itself.
Show solution and explanation
marks = 43
if marks >= 50:
print("Pass")
else:
print("Fail")43 >= 50 is False, so Python skips the if block and runs the else block. Change marks to 50 and watch the TRUE path light up instead.
Watch the solution step by stepExercise 2
Even or odd
Print whether a number is even or odd.
n = 7
# hint: n % 2Hint
n % 2 gives the remainder after dividing by 2.
Show solution and explanation
n = 7
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")7 % 2 is 1, so the condition 1 == 0 is False. Even numbers leave a remainder of 0.
Watch the solution step by stepExercise 3
Grade with elif
Give grade A for 80+, B for 60+, C for 40+, otherwise F.
marks = 65
# use if / elif / elif / elseHint
Check the highest grade first; Python stops at the first True condition.
Show solution and explanation
marks = 65
if marks >= 80:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "F"
print(grade)65 >= 80 is False, then 65 >= 60 is True, so grade becomes B and the remaining checks are skipped. Order matters: putting >= 40 first would wrongly give C.
Watch the solution step by step