How to Execute a Loop While a Given Condition is True
The while
loop repeatedly executes a block of code as long as the specified condition is True
.
Structure of a while loop
while condition:
code block
After the while
keyword, you must specify a condition followed by a colon (:)
.
Code Example
The following example executes the code block until the condition counter < 5
becomes false, meaning until counter
reaches 5
.
Example of a while loop
counter = 0
# Repeat until the condition becomes False
while counter < 5:
print(counter)
counter += 1
# Output: 0, 1, 2, 3, 4
By utilizing the while loop’s ability to repeat until a condition is met, you can continuously prompt the user for input until a specific message is entered.
Example of handling user input
# Variable to store user input
user_input = ""
# Repeat until the user enters 'exit'
while user_input.lower() != "exit":
# Receive user input
user_input = input("Enter 'exit' to quit: ")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.