Skip to content
CodeNest

Control FlowLesson 6 of 1914 min

if, elif, else

Branch your program down different paths, and understand why indentation is part of the syntax.

By the end you will be able to

  • Write if / elif / else chains
  • Use indentation to define a block
  • Choose the right ordering for overlapping conditions

An if statement runs a block of code only when its condition is truthy. Note the colon at the end of the line and the indented block beneath it.

Python
Output
It is hot.
Drink water.
This always runs — it is not indented.
— expected output; press Run to execute it yourself

Adding alternatives

else catches everything the if did not. elif ("else if") adds more tests in between. Python checks them top to bottom and stops at the first match — at most one block ever runs.

Python
Output
Score 78 earns a C
— expected output; press Run to execute it yourself

Nesting

An if can contain another if. Useful, but each level of indentation costs the reader something — if you find yourself three or four levels deep, consider combining conditions with and or extracting a function.

Python
Output
Welcome back.
— expected output; press Run to execute it yourself

Exercise

Write a function fizzbuzz(n) that returns "FizzBuzz" if n divides by both 3 and 5, "Fizz" if only by 3, "Buzz" if only by 5, and otherwise the number itself as a string.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.In an if / elif / elif / else chain where two conditions are both True, how many blocks run?
  2. 2.What ends an indented block in Python?