Free visual Python lesson

Python if / else — Explained Visually

An if statement lets Python make a decision. Press Play and watch the condition turn TRUE or FALSE, and see which block runs.

Python code

1x = 10
2
3if x > 5:
4 print("Greater")
5else:
6 print("Smaller")

Variables / Memory

Memory is empty.

Execution

STEP 1 / 6Step 1 of 6. Program starts.

Program starts.

Output

Flow chart

RanNowTrueFalseChecked, not taken◇ decision · ▱ input/output
StartStartx = 10x = 10x > 5?x > 5?print("Greater")print("Greater")print("Smaller")print("Smaller")EndEndTRUEFALSE

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 or else.
  • 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 here
Hint

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 step

Exercise 2

Even or odd

Print whether a number is even or odd.

n = 7
# hint: n % 2
Hint

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 step

Exercise 3

Grade with elif

Give grade A for 80+, B for 60+, C for 40+, otherwise F.

marks = 65
# use if / elif / elif / else
Hint

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

Try your own code

Paste any code into the free visualizer, or sign up free for all visual lessons with quizzes and progress tracking.