Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 2 · Lesson 2 · Core

if and else: running lines only when a condition is true

Write if and else blocks with the colon and the indentation Python needs.

  • 50 minutes
  • Serves O3
  • Assumes M2.L1

Phase 1: Prepare

Step 1 Warm-up recall

From M2.L1: what is the difference between = and ==?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • write an if statement with a colon and indentation (Foundation);
  • add an else branch (Core);
  • trace which lines run for a given input (Core).

Phase 2: Teach

Step 3 A familiar example

A shop checks one thing at the till: is the customer buying 10 or more items? If yes, a discount applies; if not, the full price. The program makes the same choice.

Step 4 Clear explanation

An if statement runs its lines only when the condition is True. The condition ends with a colon, and the lines to run are indented by four spaces. The indentation is how Python knows which lines belong to the if.

Conditionage >= 18Trueif blockFalseelse blockNextrest of program
The if statement runs its indented lines only when the condition is True; else runs when it is False.
age = int(input("Age: "))
if age >= 18:
    print("Adult")
else:
    print("Minor")
print("Done")

If the user types 20, the output is:

Adult
Done

If the user types 15, the output is:

Minor
Done

The last line is not indented, so it runs in both cases. else has no condition of its own: it catches everything the if did not. If you leave out the colon or the indentation, Python stops with an error before running anything.

Step 5 Worked example (4 marks)

Trace n = 7 then if n % 2 == 0: print("even") else: print("odd").

  1. n % 2 is the remainder of 7 divided by 2, which is 1. (1 mark)
  2. 1 == 0 is False, so the if block is skipped. (1 mark)
  3. The else block runs. (1 mark)
  4. Answer: odd. (1 mark)

Go deeper: the professor's notes

Python uses indentation to show what belongs to an if, which prevents the duplicated-line slip.
Colon

Opens the block.

Indent

Marks membership.

Dedent

Ends the block.

ifcondition:IndentbodyDedentnext lineTestboth paths
Block

Check

LineRuns when
indentedcondition True
not indentedalways

At work: A check that never runs

A line is meant to run only for errors.

  1. Indent it under the if.
  2. Test with a failing and a passing input.

What a careful practitioner decides. Indent by four spaces and test both paths.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. The line that starts an if statement must end with:

2. Python knows which lines belong to the if by:

3. The else block runs when:

4. With n = 10, what does if n % 2 == 0: print("even") else: print("odd") show?

Phase 4: Close

Step 7 Recap

  • if runs its indented lines only when the condition is True.
  • else catches the False case.
  • The colon and indentation are required.

Step 8 Exit ticket (ungraded)

Write an if and else that prints Pass when score >= 50 and Fail otherwise.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that asks for a number and says whether it is even or odd.

In industry: goto fail: one duplicated line

In February 2014 Apple released iOS 7.0.6 to fix a security flaw in how devices checked secure connections. A second goto fail line sat under the if, indented as if it belonged to it, but it ran every time. That skipped the final check, and the flaw had existed since iOS 6.0 in 2012.

Link to this lesson. In C the indentation does not decide what belongs to an if. In Python it does, which is why Python makes you indent the block.

Source: ImperialViolet, Apple SSL/TLS bug (22 Feb 2014); ACM, Finding more than one worm in the Apple

Common mistakes

MistakeWhy it fails
Forgetting the colonEnd the if and else lines with a colon.
Not indenting the blockIndent the lines that belong to the if.
Putting a condition after elseelse has no condition; use elif for another check.

Limits. Examples use four spaces of indentation, which is the common convention.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · What must an if line end with, and how do you mark its block?
ifcondition:Indentfour spacesDedentends block
if block

It ends with a colon, and the lines to run are indented by four spaces. The indentation is how Python knows which lines belong to the if.

Card 2 of 3 · When does else run?
ifTrue pathelseFalse pathNextrest
else

When the if condition is False. else has no condition of its own. It is the safe default path in a program, for example refusing a request that failed every check.

Card 3 of 3 · What does elif add?
ifcase 1elifcase 2elserest
elif chain

More cases between if and else. Python runs only the first block whose condition is True. A pricing program with three bands uses if, elif, else.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards