Python While Loops: Common Errors and How to Fix Them

Olamide 'Pearl' Makinde
5 min readNov 10, 2021

--

A Python programmer coding on her laptop with a book by her side.

Loops are effective timesavers; they allow you to instruct the computer to perform one function multiple times without repeating the code. While Loops are a type of loops in Python. They ask your computer to repeat the execution of a code for as long as a specified condition is met.

I just thought to mention that I’m writing this article out of frustration. My code refused to run; I kept going from one error to another until my friend, Olumide, came to my rescue. Yes, I’m a Python newbie, and I just never have my while loop running at one go. Using an example, I’ll discuss common errors I (and some other Python programmers) make while creating While Loops.

Uninitialised Variables

Just before your While Loop, you have to assign an initial value to your variable. This means you are initialising the variable. It serves as the base on which a function in your While Loop will run, a line you’d reference in your loop. Omitting the variable initialisation will return an error. Let’s see an example:

In this example, we want to create a multiplication table. To make the result short, we’ll only loop through to 5, i.e. “number x 1” to “number x 5”.

First, we declared a function of a number and titled it times_table. Say “3 x 4 = 12”, “3” is the number, “4” is the multiplier, and “12” is the expected result. The multiplier would be accounted for by the while loop “while multiplier <=5”. It indicates that the multiplication would stop at 5, as stated in the previous paragraph. The result would be provided from the expression in our loop, and we can input different numbers.

def times_table(number):
#Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
times_table(3)
A screenshot of the IDE
Code Screenshot: Initialisation Error

Error: Oops! It doesn’t work. The error states, “local variable ‘multiplier’ referenced before assignment”. It simply means that we didn’t initialise our multiplier variable. The line “while multiplier <= 5:” cannot work in this case because our multiplier hasn’t been set. Likewise, the line “multiplier += 1”, which means “new multiplier = old multiplier + 1”, will not work because there’s no set “old” multiplier for our first iteration.

Fix: We want our multiplier to begin from 1, so we’ll set our initial variable to 1. The fix is highlighted in the snippet below.

def times_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1

# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
times_table(3)
A screenshot of the IDE
Code Screenshot: Correction

Omitting the Increment Line

The “while multiplier <= 5:” line asks the computer to repeat the execution as long as the variable is lower than or equal to five. However, we need to specify the increment, else the code will keep running in an infinite loop and won’t even count. Using the same function, see the code below:

def times_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
print(str(number) + "x" + str(multiplier) + "=" + str(result))
times_table(3)

Can you spot the error?

A screenshot of the IDE
Code Screenshot: No Increment Error

Error: It gives an unintended infinite loop and the multiplier doesn’t increase. We have “ 3 x 1 = 3” in numerous places.

Fix: We include the “multiplier += 1” line. It tells the computer, “for this current iteration, the “new multiplier” = “old multiplier” + 1". And it’ll continue to increase by 1 per iteration while it’s ≤5. The fix is highlighted in the snippet below.

def times_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
times_table(3)
Code Screenshot: Solution

Wrong Indentation

In some programming languages, you can indent to make your code look neat and readable without directly affecting your semantics. Python, however, takes indentation seriously. It tells the computer that the subsequent lines of code with similar indentation belong to a block. The wrong indentation will return an error. Using the same example, let’s see the snippet below.

def times_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier

print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
times_table(3)

Error: The “result = number * multipliershould be indented. Not indenting it gives an error which states “IndentationError: expected an indented block”.

Screenshot of the IDE
Code Screenshot: Indentation Error

Fix: Add a tab or few spaces to the right before the result expression. Ensure that it’s the same amount of space before the result expression, print statement, and increment specification, because they belong to the same block of code. If you do not use the same indent on the multiplier line, it’ll result in an infinite loop. The fix is highlighted in the following code snippet.

def times_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier

print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
times_table(3)

View the code here.

The Correct While Loop Checklist

When creating your While Loop,

  • Initialise your variable.
  • Use the correct indentation.
  • Remember to specify the increment.
  • Use a stopping criterion where necessary.
  • Remember to use a colon after your while statement.
  • Confirm you’re using the accurate logical operator.

If your code returns an error, read the error. It’ll help you deduce where the mistake is and fix it.

--

--

Olamide 'Pearl' Makinde
Olamide 'Pearl' Makinde

Written by Olamide 'Pearl' Makinde

I kinda just like to rant here + I write tech stuff sometimes. I love hearing my readers’ thoughts; we can have a convo in the comment section, twitter, or IG.