Lesson 9: Python While Loop

While Loop is another powerful repetition structure in Python.

Its main difference from For Loop is that:

  • For Loop iterates for a fixed amount of time
  • While Loop iterates as long as its logical statement is satisfied (It can run infinitely if the statement doesn’t change)

Let’s start with an example:

Example 1: While loop with infinite loop

  • In this example condition satisfied the loop so it starts executing but condition never changes so it enters an infinite cycle and never stops iterating. This is called an infinite loop in programming.
i=1

while i==1:
    print("Hello World!")

Runtime Error (Infinite Loop)

  • Infinite loops have a place in programming and they are useful in specific cases. For example in GUI applications. You might want to show program’s user interface “infinitely” until user clicks exit. If you ever have a chance to take a look at this program’s source code you will see how gui is shown with infinite while loop.

Above code will run infinitely and this would cause a nuisance and potentially a minor crash in your compiler.

What happens is compiler checks if 1==1 which is True so it runs the line print(“Hello World!”).

Then it goes back and checks if 1==1 again and prints again and so on. The code inside while loop will be iterated continuously until the necessary condition to run the loop isn’t met (i <>1).

That’s why while loops are often used with counter variables and it’s common to increase the value of counter in every iteration so the loop can eventually be triggered to exit.

This whole concept will be more clear after a few examples and as usual practice makes perfect 🙂. For that don’t forget to have some fun with the Python while loop exercises we have prepared for you.

* For logical statements or conditional statements in Python, double equal sign is used (==) this is different than assignment operator (=) which is used to assign a value to a variable. Feel free to check this page if you’d like to see a full list of Python Operators.

Oh btw, have you heard of the programmer that got stuck in the shower? Because shampoo instruction said: Lather, Rinse, Repeat. 😂 

Example 2: While loop with counter

  • This example is programmed to iterate only three times because at the end of each iteration counter is bumped up once, and once it hits 3 it won’t satisfy the loop causing the loop to end.
i=0

while i<3:
    print("Hello World!")
    i = i+1

Hello World!
Hello World!
Hello World!

  • Great, I think the world hears you now 😉

Used Where?

Loops are great tools for handling repetitive tasks. 

While Loops are particularly useful when you don’t know how many iterations will be appropriate exactly. Sure for loop is handy when you have a list of five items and you want to do a math operation to each item. But there can be ambiguous tasks a programmer wants to handle.

Check out these examples in pseudo syntax for demonstration:

  • while (mouse_is_moving):
    • do something
  • while (lights_are_on):
    • some action
  • while (team_is_winning):
    • another statement
  • while (user_age < 18):
    • action

These are only some vague ideas about the type of situations while loops can be preferred to for loops.

Syntax do(s)

1) First line starts with while followed by a statement

2) There is a colon(:) at the end of first line

3) After first line following lines should be indented

Syntax don't(s)

1) Don't forget the colon (:) at the end of the first line just like for loops

2) Don't forget the indent after the first line also just like for loops

3) Unintentional infinite loops are extremely common with while loops. So, don't forget to increase the counter variable after your iteration or implement another way to exit the loop eventually.

Tips

1- When you forget to include the operation (such as i = i+1) that causes the loop to exit, your code will loop forever.

If this happens just interrupt your compiler so that your code is stopped externally. Most programming software and terminals have either shortcuts (sometimes ctrl+c, ctrl+q or ctrl+z) or visual buttons to stop the code from running.

Example 3: While loop with Python dictionaries

This example is slightly more complex which is why it’s a great opportunity to master a few Python topics.
  • Let’s say World Bank is offering startup grants for middle age founders (let’s say age range is defined as people between 25 and 55 inclusive).
  • Using while loop, let’s create a new dictionary that has people’s names as keys and True or False as key values (based on eligibility for World Bank funding)
  • We need a new dictionary with names as keys and boolean value as their application pre-filtering. Imagine you have ~2 million applicants. It will take bureaucrats a couple of decades to go through the list. But we need the dictionary today!
  • We couldn’t simply iterate through the dictionary because Python dictionaries don’t have an indexed structure. But as you see there is always a way in programming.

    In case you want to review dictionaries we have this Python Dictionary Lesson. Also, lists are involved in this example 👉 Python Lists.

dict_1 = {"Jingyi": 24, "Rishaan": 21, "Cloe": 35, "Amir": 32, "Mayumi": 18, "Peter": 42}

lst = list(dict_1.keys())

i=0
dict_2 = {}
while i < len(lst):
    if 25 < (dict_1[lst[i]]) < 55:
        dict_2[lst[i]] = True
    else:
        dict_2[lst[i]] = False
    i+=1
 
print(dict_2)

{‘Jingyi’: False, ‘Rishaan’: False, ‘Cloe’: True, ‘Amir’: True, ‘Mayumi’: False, ‘Peter’: True}

Are you super comfortable with this Python example? How about trying the same thing with Python For Loops?

Function : Python len function

We will use Python’s len function to iterate through a list with Python’s while loop.

Example 4: While loop vs For loop

How about using while loop to iterate through a list? This is possible with the help of len function but, it’s just so much more convenient to use a for loop for such tasks. Take a look:

lst = [3, 5, 9, 11]

i=0
while i < len(lst):
    print(lst[i])
    i = i+1

3
5
9
11

I think this example is really good because it helps you understand the for loop better while learning while loop.

* Do you realize how iterator (we named it “i” here) is different than for loop’s case? Here it’s just a number we created, in for loop it would be the items themselves in the collection. That’s why we’re using lst[i] in print function instead of just “i”.

** By the way i is just the name we give to the iterator variable. It can be any other reasonable name (but not the Python’s reserved keywords) like iter or anything else.

If these concepts are not solid for you, you might really want to practice them through exercises. Also for a while it’d be helpful to keep coming back to exercise until you feel really comfortable with it. They are also really fun.

Advanced Concepts: Nested while loop

1- In some situations nested loop structures can be useful. We have previously seen that lists can consist of different type of data including other lists. Let’s see an example of nested list and nested while loop to print each of its items.

Example 5: Nested While Loop

Let’s create a while loop structure which prints (Message1) once and then (Message2) twice. And then does this block whole thing three times.

We will use two separate counters, let’s name them i and j.

i = 0
while i<3:
    print("Outer Loop")
    j = 0
    while j<2:
        print("Inner Loop")
        j = j+1
    i = i+1

Outer Loop
Inner Loop
Inner Loop
Outer Loop
Inner Loop
Inner Loop
Outer Loop
Inner Loop
Inner Loop

As you can see outer loop runs 3 times (while i is 0, 1 and 2). And the inner loop runs twice (while j is 0 and 1)

Also pay attention to how counters are increased by one at the end of their relative iterations. This is important to get right because indentations are important in Python syntax and if you misplace even one space you will get an error. It’s not that hard but it can take some getting used to. So, this is a great opportunity for practice if Python syntax spaces are still not natural for you. Keep repeating until you are 💯 comfortable.

This is the end of our Python While Loop lesson. I hope it was useful for you. If you are a brand new coder feel free to check out our exercises and keep repeating them until everything starts becoming a natural instinct for you. You can find the link below.

Also another coding practice idea for while loops is to check out our Python For Loop Exercises and try to achieve each of their solutions using while loops.

Good luck!

Next Lesson