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.
It is hot.
Drink water.
This always runs — it is not indented.
— expected output; press Run to execute it yourselfAdding 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.
Score 78 earns a C
— expected output; press Run to execute it yourselfNesting
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.
Welcome back.
— expected output; press Run to execute it yourselfExercise
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.
Press Run to execute this code.