11) User Input and String Formatting Lesson

Python While Loop

12 min to complete · By Martin Breuss

There are two different kinds of loops in Python. You can use them to do different types of iteration:

  1. Definite iteration: for loop
  2. Indefinite iteration: while loop

You've already learned about the for loop in the previous section, and now you'll get to know the while loop.

You can do the same with either of the two types of loops. However, they have preferred applications. When for loops are much more common in practice, one good application of while loops is when you are asking for specific user input.

Python While Loop Limitation

Python's while loop has a different basic assumption than the for loop. It doesn't have an automatic stop condition built-in. for loops run only as often as there are items in your iterable. while loops don't have this limitation.

Infinite Loop

The lack of a built-in exit condition means that you need to take care to avoid accidentally creating an infinite loop:

while True:
    print("loopy, loopy, loopy...")

Don't try this at home because that's an infinite loop. It's endless. True will always be True, which means that it just doesn't stop. Just like this description of infinite loops doesn't seem to stop. Even though you already understood what an infinite loop is. It just keeps going on. Forever. That's kind of annoying, right?

Colorful illustration of a light bulb

Info: If you do want to try running this infinite loop, just go ahead! There's actually no danger associated with it, and you won't break anything. Just be ready to quit your text editor once it gets stuck.

An infinite loop in programming describes a program that keeps running without ever being able to stop.

Because indefinite loops, such as the while loop, don't have an exit condition built-in, you might end up creating infinite loops by accident. When you're starting out, it's, therefore, easier to begin with using for loops that end by themselves.

Apple Campus Sign
Colorful illustration of a light bulb

Info: Apple's campus is called the infinite loop. Probably because it's a circle-shaped building, and very likely also as a joke for the resident programmers. The campus was definitely not created by accident ;)

However, there are some good reasons for using while loops, such as collecting user input for a game. Get ready to pick one specimen apart to make sure that you understand how it works.

Python While Loop Functionality

When taking apart a while loop, you might see that it shares more similarities with a conditional statement than with the for loop. To start dissecting, you'll first need a while loop to pick apart, so here's a really annoying one for you to try out:

name = None

while name != "your name":
    name = input("Please type your name: ")

print("Finally!")

Can you see what this loop does and where the joke lies? Save it to a file and give it a go. It's not a great joke, but it'll do for learning about the anatomy of the while loop :)

The program starts by creating the name variable and setting it to the value None. This is necessary so that the first iteration of your while loop will be able to compare its value to "your name". After the first go-around, the name variable will point to whatever input your user gave this time around.

The first line of the while loop represents the loop statement. You'll pick it apart just like you did with the for loop. As you might see, it shares similarities with both a conditional statement and a for loop.

Three Components of a While Loop

There are three main components to the while loop function definition.

1. While keyword

This is the same in each while loop. It's the signal for Python that what follows should be interpreted as a while loop.

2. Conditional Statement

Take (name != "your name") as an example. This expression evaluates either to True or to False.

name needs to point to an existing variable otherwise Python will get confused. The result of this expression decides whether the while loop will continue or not.

3. Ending Colon

The colon is Python's indicator that the first line of your while loop is ending. Which also means it opens up the body of the while loop.

You might notice that this looks similar to an if statement. It might help to think of a while loop as a repeatedly evaluated if statement, where one of the values of the condition can change inside the loop body.

As long as the expression keeps evaluating to True, the loop keeps going. Once it evaluates to False it stops immediately and continues execution after the body of the while loop.

This brings you to the second line of code in this loop, which represents the loop's body. It consists only of one line of code, but just like with the for loop, there could be many more. Anything that is indented four spaces is considered to be part of the loop body.

While Loop Exit Condition

What makes the while loop interesting is that it needs to have a possible exit condition built in. While your loop runs, it needs to be able to change one of the variables that make up the conditional check in the while loop's opening statement.

Colorful illustration of a light bulb

Note: If there is no such possibility, then you're dealing with an infinite loop.

In the case shown above, there is an option for the conditional check to change its outcome. Every time the user submits an input, the name variable changes, giving the conditional check name != "your name" a chance to return False and end the while loop.

The only option for the check to return False, is when the user enters the exact string "your name". Until they get the joke and do so, the while loop will just continue to ask the same question.

The Rest Of The Script

The final line of code in this script is a concluding print():

print("Finally!")

You can see that this line is not indented, which means that it isn't part of the loop body. This line will only execute once the while loop has stopped the execution, which will only happen when the user inputs the correct string.

As soon as the condition in your while loop has evaluated to False only once, the loop is left behind and any remaining code in your script that follows the loop will run.

Practice While Loops

  • Pick apart the whileloop in the guess-the-number game. Make sure you understand what's going on.
  • Emulate the functionality of a for loop using a while loop. How can you create an exit condition that stops the loop after a set amount of cycles? Play around with the example code for support.
Colorful illustration of a light bulb

Additional Resources

Summary: While Loop Python Function

  • The while loop allows an indefinite iteration in Python
  • If an exit condition is not provided, then the while loop will continue indefinitely
  • Infinite loops will break a program
  • The while loop conditional statement evaluates to True or False
  • While loops are great for receiving user input

Three Components of a While Loop

  1. while keyword
  2. Conditional statement
  3. Ending colon