Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 3 of 10

Everything so far has run top to bottom, every line, every time. An if statement breaks that: it runs a block of code only when a condition is True.

age = 20

if age >= 18:
    print("You may enter.")

Two details matter enormously in Python:

  1. The line ends with a colon (:).
  2. The body is indented — four spaces by convention. Indentation is not decoration in Python; it is how the language knows which lines belong to the if.

else

else runs when the condition was False.

age = 15

if age >= 18:
    print("You may enter.")
else:
    print("Sorry, too young.")

Exactly one of those two branches will run — never both, never neither.

elif

For more than two possibilities, use elif ("else if"). Python checks each condition top to bottom and runs the first one that is True, then skips the rest.

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")

Because Python stops at the first match, order matters. If you put score >= 70 first, a score of 85 would print C — the >= 80 check would never be reached.

Indentation errors

This is the most common beginner error in Python:

age = 20
if age >= 18:
print("You may enter.")

That raises IndentationError because the body was never indented. Keep the four spaces consistent.

Try it yourself

The grader below uses a score of 85. Run it, then change score to 95 and to 42 to watch a different branch win each time.

Checkpoint

  • if runs a block only when its condition is True.
  • elif adds more conditions; else catches everything left over.
  • Python picks the first true branch and skips the rest.
  • The colon and the indentation are both required.

Questions about this lesson

Log in to ask a question.