0
0
Pythonprogramming~5 mins

Why while loop is needed in Python

Choose your learning style9 modes available
Introduction

A while loop helps repeat actions as long as something is true. It saves time and avoids writing the same code again and again.

When you want to keep asking a user for input until they give a correct answer.
When you want to keep running a game until the player loses or quits.
When you want to repeat a task until a certain condition changes, like counting down to zero.
When you don't know how many times you need to repeat something before starting.
Syntax
Python
while condition:
    # code to repeat
    # update condition or break

The condition is checked before each repeat.

If the condition is false at the start, the code inside the loop won't run at all.

Examples
This counts down from 3 to 1, printing each number.
Python
count = 3
while count > 0:
    print(count)
    count -= 1
This keeps asking the user to type 'yes' before moving on.
Python
answer = ''
while answer != 'yes':
    answer = input('Type yes to continue: ')
Sample Program

This program counts down from 5 to 1 and then prints 'Done!'. It shows how while repeats until the count reaches zero.

Python
count = 5
while count > 0:
    print(f'Counting down: {count}')
    count -= 1
print('Done!')
OutputSuccess
Important Notes

Always make sure the condition will become false at some point, or the loop will run forever.

You can use break inside a while loop to stop it early.

Summary

While loops repeat code as long as a condition is true.

They are useful when you don't know how many times to repeat before starting.

Make sure the loop will stop eventually to avoid infinite loops.