Learn the basics of while loops in Python.
Loops are one of the fundamental constructs that enable us to control the flow of our program. A while loop is a type of loop that repeats a block of code while a specific condition is true. While loops are perfect for when we want to repeat code an unknown number of times.
We actually use while loops in our everyday lives all the time:
In these examples, we’re not quite sure when the road will curve or when exactly the temperature is going to change. So, we continue driving straight until the road curves, or we keep the heat on until the temperature is higher than 68 degrees.
A while loop in Python looks like this:
If the condition evaluates to true
, the code inside the loop will execute. Once the condition evaluates to false
, the computer will exit the while loop and continue on with the program. Click through the slides to walk through a while loop in action.
Look at the example program below. In plain English, it says while there are more than 0 tacos, eat a taco. Run the program and explore with these guiding questions:
num_tacos
?num_tacos < 0
?Take a look at the While Loops Guessing Game below. Before running the program, predict what you think will happen. What is the while loop condition in plain English? When will the while loop end? (If you are unfamiliar with the !=
symbol, check out the Booleans and Logical Operators tutorial.
When writing a while loop, beware of the infinite loop! An infinite loop occurs when the condition is always true. When there is an infinite loop, the computer will attempt to run the while loop forever, which will ultimately result in crashing the browser or an error.
Let’s revise our tacos program slightly. Look closely - can you figure out why this program would result in an infinite loop?
A hint that you might have an infinite loop on your hands is if you don’t change the value of the variable in the condition. In the above program, we never change the value of num_tacos
in our loop. This means that num_tacos
will always be 5, which also means that the condition num_tacos > 0
will always be true. When the computer runs the program, it will end up repeating the loop an infinite number of times because the condition always evaluates to true
and there is no way to exit the loop.
Which of the following would result in an infinite loop?
Practice your hand at while loops by completing any (or all!) of the following challenges:
Level 1: Write a while loop that prints a countdown from 10.
Level 2: Write a program that goes from 100 to 0 at different intervals specified by the user. You can use the int(input("prompt"))
command to get a number from the user. Your sample output might look like this: