While Loop in Python
The while loop is a powerful tool for repeating code as long as a condition remains true. It's ideal when you don't know exactly how many times the loop needs to run – for example, waiting for user input or processing data until a certain goal is reached.
The loop checks the condition before each iteration. If it's true, the code block runs. If false, the loop stops.
Always make sure the condition will eventually become false – otherwise you get an infinite loop!
Basic While Loop Syntax
The structure is simple: while (condition): followed by an indented block.
You usually update a variable inside the loop to make the condition false eventually.
Without count += 1, the loop would run forever (infinite loop).
Counting Down
While loops are great for countdowns.
Infinite Loops – How to Avoid Them
An infinite loop runs forever because the condition never becomes false. Our editor has protection (timeout and iteration limit), but in real programs it can freeze everything.
Common causes: forgetting to update the condition variable, or wrong condition.
Loop Control Statements
break – Exit the Loop
break immediately stops the loop, even if the condition is still true.
continue – Skip to Next Iteration
continue skips the rest of the current iteration and goes to the next one.
else Clause
The else block runs when the loop finishes normally (condition becomes false) – but not if break was used.
Do-While Pattern (Simulation)
Python doesn't have a built-in do-while loop (run at least once before checking condition), but you can simulate it with while True and break.
Real-World Examples
Example 1: Password check with limited attempts
Example 2: Simple game loop
Quick Quiz
Az anyagokat átnéztük és ellenőriztük, de hibák továbbra is előfordulhatnak. A tartalom kizárólag oktatási célt szolgál, ezért saját felelősségre használd, és szükség esetén ellenőrizd más forrásokkal is.
✨ Kérdezd Larát — a tanulási partnered
Fedezd fel a személyre szabott tanulási támogatást. Lara elmagyarázza az anyagot, összefoglalja a témákat és megválaszolja a kérdéseidet — az Go csomagtól elérhető.
Lara segít gyorsabban tanulni — kizárólag a ReadyTools Go, Plus és Max tagoknak.

