Lesson 14 of 4035%
(Progress persistence is disabled until Phase 9)
Python
Beginner
while Loops
Repeat code as long as a condition is true.
while Loops
What You’ll Learn
You’ll learn how to execute a set of statements repeatedly using a while loop.
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
i = 1
while i <= 5:
print(i)
i += 1 # This is crucial!
Expected Output:
1
2
3
4
5
The Infinite Loop Danger
Remember to increment i (or change whatever variable your condition relies on). If you forget i += 1, the condition i <= 5 will always be true, and the loop will run forever! This will crash your program.
When to use while loops?
while loops are best when you don’t know exactly how many times you need to loop beforehand. For example, asking a user for input until they provide a valid response.
password = ""
while password != "secret":
password = input("Enter the password: ")
print("Access Granted!")