While Loop in Python

SchleifenFor-Schleife

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

Wir haben die Materialien überprüft, dennoch können Fehler vorkommen. Der Inhalt dient ausschließlich Bildungszwecken, daher verwende ihn auf eigene Verantwortung und überprüfe ihn bei Bedarf mit anderen Quellen.

✨ Frag Lara — deine KI-Lernpartnerin

Entsperre personalisierte Lernunterstützung. Lara kann Lektionen erklären, Themen zusammenfassen und deine Lernfragen beantworten — verfügbar ab dem Go-Tarif.


Lara hilft dir, schneller zu lernen — exklusiv für ReadyTools Go-, Plus- und Max-Mitglieder.

Verfolge deinen Fortschritt 🚀

Lerne einfacher, indem du deinen Fortschritt kostenlos verfolgst.