Ch 7 · Loops & Iterations · Python
Topic 7 of 13 in Python — Complete Tutorial (Beginner) — 4 lessons.
Why We Need Loops
Computers are brilliant at repetition — something humans find tedious. A computer can perform the same operation a million times in a fraction of a second without getting tired or making mistakes. A loop is a construct that runs a block of code repeatedly, automatically, without you writing it out many times. Without loops, printing the numbers 1 to 100 would need 100 lines; with a loop, it needs just two.
The for Loop and range()
The for loop in Python is built to walk through collections. You write for item in something: and Python automatically gives you each element in turn. To loop a specific number of times, you pair it with the range() function, which generates a sequence of numbers. range(1, 6) produces 1, 2, 3, 4, 5 — it stops just before the second number. You can also give range a step to count by twos, or count backwards.
The while Loop
The while loop keeps running its indented body as long as a condition stays true. Unlike the for loop, it has no built-in counter — you manage the change yourself inside the loop. This makes it flexible: the stopping condition can be anything, not just counting. The most important rule is to make sure the condition will eventually become false, otherwise you create an infinite loop that runs forever and freezes your program.
break and continue
Sometimes you need to exit a loop early, or skip one repetition without stopping the whole loop. The break keyword immediately ends the loop — useful when searching and you have found what you wanted. The continue keyword skips the rest of the current repetition and jumps to the next one — useful for ignoring certain values while processing the rest. Python has no do-while loop, but you can recreate one with while True: and a break.
All topics in Python Beginner
- Introduction to Programming & Python
- Your First Python Program
- Variables — Your Data Containers
- Data Types — Kinds of Values
- Operators & Expressions
- Conditional Statements
- Loops & Iterations
- Functions
- Lists — Collections of Data
- Dictionaries & Classes
- Strings — Working with Text
- Error Handling
- Mini-Projects & Practice