0
0
Pythonprogramming~5 mins

While loop execution flow in Python

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves time by automating repeated tasks.

When you want to keep asking a user for input until they give a valid answer.
When you want to count or do something repeatedly until a certain number is reached.
When you want to keep checking if a condition is true before stopping.
When you want to run a game loop that continues until the player quits.
Syntax
Python
while condition:
    # code to repeat
    # update condition or variables

The condition is checked before each loop. If it is true, the code inside runs.

If the condition is false at the start, the code inside the loop does not run at all.

Examples
This prints numbers 0, 1, 2 by increasing count each time until count is no longer less than 3.
Python
count = 0
while count < 3:
    print(count)
    count += 1
This keeps asking the user to type 'exit' to stop the loop.
Python
user_input = ''
while user_input != 'exit':
    user_input = input('Type exit to stop: ')
Sample Program

This program prints numbers from 1 to 5. The loop runs while the number is 5 or less. Each time, it prints and then adds 1 to number.

Python
number = 1
while number <= 5:
    print(f"Number is {number}")
    number += 1
OutputSuccess
Important Notes

Make sure to change something inside the loop that affects the condition, or the loop will run forever.

You can use break to stop the loop early if needed.

Summary

A while loop repeats code as long as a condition is true.

The condition is checked before each repetition.

Update variables inside the loop to eventually stop it.