Loops in Python
Loops are a fundamental part of programming. They allow you to repeat a block of code multiple times without writing it over and over.
In real programs, repetition is everywhere: processing items in a list, counting, waiting for input, drawing patterns, or running animations. Loops make these tasks efficient and keep your code clean.
Python has two main loop types:
- while loop – repeats as long as a condition is true
- for loop – repeats over a sequence (like a list or range of numbers)
Both use indentation to define the block of code that repeats. We'll start with a general overview, then dive deeper into each type in the following lessons.
Why Loops Are Important
Without loops, simple tasks would require writing the same code many times. For example, printing numbers 1 to 100 manually would mean 100 print statements!
Loops solve this by automating repetition. They also make code more flexible – change one number and the whole behavior updates.
Common Loop Patterns
You'll use loops for:
- Counting up or down
- Processing every item in a collection
- Repeating until a condition is met
- Building patterns or tables
- Game logic and animations
Loop Control Statements
Python provides tools to control loops:
- break – exit the loop early
- continue – skip to the next iteration
- else clause – runs when the loop finishes normally (not with break)
Simple Example – Repeating a Message
Here’s the same task with both loop types.
Using while:
Using for with range:
Both produce the same output – choose based on whether you know the number of repetitions in advance.
When to Use Which Loop
while loop: Use when the number of repetitions is unknown – like waiting for user input or until a condition changes.
for loop: Use when you know how many times to repeat or are looping over a sequence (list, string, range).
Avoiding Infinite Loops
An infinite loop runs forever because the condition never becomes false. Our editor has protection, but always make sure your loop has a way to stop.
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.

