PYTHON BASICS
Python Basics: Repetition
Control Flow — Part 2
In the last article, we saw how the if-statement enables us to write programs that can choose what actions to perform based on certain specified conditions. We were able to write a program that classified our age into the appropriate age group by choosing which line of code to execute.
Railroad Analogy
Recall the railroad analogy for if-statements, where each track represents a path that the program can take. A program without conditional statements has only one path of execution from start to finish. Conditional statements make it possible for a program to execute in one of many ways. The if-statement is a switch that determines a path that the program will proceed through: This act of choosing between multiple paths is known as conditional branching.
While Statement
In addition to the if-statement, an equally important structure for altering the control flow of a program is the while-statement. A while-statement performs an action multiple times, and we can control how often the action is repeated using a specified condition.
Let’s illustrate the need for repetition with an example.
Fizz Buzz
According to Wikipedia, Fizz Buzz is a game where players count up from 1, replacing numbers divisible by 3 with Fizz, numbers divisible by 5 with Buzz, and numbers divisible by both 3 and 5 with FizzBuzz. All other numbers are called out as they are.
1 1
2 2
3 Fizz
4 4
5 Buzz
6 Fizz
7 7
8 8
9 Fizz
10 Buzz
11 11
12 Fizz
13 13
14 14
15 FizzBuzz
16 16
17 17
18 Fizz
19 19
20 BuzzIn this example, we are counting from 1 to 20, applying the rules of the game to each number. Since 1 is not divisible by 5 or 3, it is called as it is. The number 3 is divisible by 3, therefore it is called out as Fizz along with all multiples of 3. Similarly, the number 5 and its multiples are called out as Buzz. The exception to this rule is the number 15. Since it’s both a multiple of 3 and 5, it gets called out as FizzBuzz.
With what we know, we could implement the rules for any number in the following manner:
number = ... # replace with any number
is_divisible_by_3 = (number % 3 == 0)
is_divisible_by_5 = (number % 5 == 0)
if is_divisible_by_3 and is_divisible_by_5:
print("FizzBuzz")
elif is_divisible_by_3:
print("Fizz")
elif is_divisible_by_5:
print("Buzz")
else:
print(number)Recall from Python Basics: Arithmetic Operation that the % operator computes the remainder of the division between two numbers. We know that a number is divisible by another number when there is no remainder after dividing. In this case, number % 3 == 0 is True when number is divisible by 3, and False otherwise.
Although this program works for a single number, we want to repeat this process 20 times, as in the example above. We could Copy + Paste the code 20 times, but that would be quite tedious. Moreover, it would be rather inefficient if we want to count to 100, or even 1,000.
Get Gideon Oludeyi’s stories in your inbox
Join Medium for free to get updates from this writer.
The while-statement provides a mechanism for repeating this process as often as we want. All we need is to specify what action to perform, as well as a condition that informs the program whether to repeat the action or to stop.
Syntax
while <CONDITION>:
... # actionUsage
number = 1
while number <= 20:
print(number)
number += 1
... # after the while statementWhen this program runs, number is initially set to 1 and we enter the while statement. In the while statement, the program checks whether the given condition is True (i.e. whether 1 ≤ 20).
Since the condition is True, the program runs the code within the while block, which outputs number and then increments it by 1. Recall from Python Basics: Conditional Statements that Python uses indentation to determine what code belongs to a given statement.
Once the code block executes, the program goes back to the beginning of the while statement to check whether the condition is True (i.e. whether 2 ≤ 20), and repeats the same code block because 2 ≤ 20 is also True.
After some time, when number becomes 20, the code block runs as expected since 20 ≤ 20 is still True. This updates the value of number to 21, and the program goes back to the beginning of the while statement. Now the condition number ≤ 20 evaluates to False because 21 is not less than or equal to 20, therefore the program does not execute the code block, but proceeds to the next instruction after the while statement.
In other words, the while-statement stops repeating the first time the condition becomes False.
Notice that we’re increasing number on every iteration of the while statement. We want to ensure that the condition will eventually evaluate to False at some point, otherwise, the while statement will repeat forever. In other words, we want number to approach a value that is not less than or equal 20.
If we instead omitted the last line in the while block or used number -= 1, the value of number would never approach 21. As a result, the while-statement would never stop.
Finally, an implementation of the Fizz Buzz game using the while-statement looks like the following:
number = 1
while number <= 20:
is_divisible_by_3 = (number % 3 == 0)
is_divisible_by_5 = (number % 5 == 0)
if is_divisible_by_3 and is_divisible_by_5:
print("FizzBuzz")
elif is_divisible_by_3:
print("Fizz")
elif is_divisible_by_5:
print("Buzz")
else:
print(number)
number += 1We initialize the number variable to 1, and specify that we want to repeat the Fizz Buzz algorithm so long as number is less than or equal to 20. The last line in the while block increases number by 1 so that the next time the while block runs, it’ll apply the Fizz Buzz algorithm on 2, 3, 4, and so on until the condition fails. By implication, the while-statement will eventually stop, since number is approaching a value that does not satisfy the condition.
Fun Exercises
How many times will each of the following while-statements run?
while True:
print("Hello world")while False:
print("Hello world")n = 0
while n < 10:
print(n)
n += 3n = 0
while n > 5:
print(n)
n -= 2Conclusion
We learned about the while-statement and how to use it to repeatedly perform actions while a certain condition holds. In the next article, we’ll be taking a look at Functions, and how to use them to improve the quality of our code.



