Guidelines

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 leveraging the characteristic of the while loop to continue repeating until a certain condition is met, you can repeatedly 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: ")
Mission
0 / 1

You need to add a colon (:) after the condition in a while loop.

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result