AiTechWorlds
AiTechWorlds
Imagine you run a small business and you need to send a letter to 1,000 customers. Each envelope needs the same return address stamped in the top-left corner. You could write it by hand — once, twice, three times... by envelope 50, your hand is cramping. By envelope 200, you've made spelling mistakes. By envelope 500, you've given up entirely.
Smart businesses use a rubber stamp. You ink it once, press it down, move to the next envelope, press it down again. Same action. Repeated. Automated.
Loops are your rubber stamp in Python.
Instead of writing the same code fifty times, you write it once and tell Python: repeat this for every item in this collection or keep repeating this until a condition changes.
This is not a small convenience. It is a fundamental superpower of programming. Loops are what allow a single developer to process a million records, generate a thousand images, or check ten thousand passwords — without writing ten thousand lines of code.
Let's say you want to print the numbers 1 through 5. Without loops, you'd write:
print(1)
print(2)
print(3)
print(4)
print(5)
Fine for 5. Now imagine 1 through 1,000. You'd need 1,000 print statements. What if the number changed at runtime — what if the user typed in how many they wanted? Without loops, that's impossible.
With a loop:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Five lines of output from two lines of code. That ratio gets more dramatic as the task grows.
for Loop: Iterating Over SequencesA for loop says: "for each item in this collection, do this thing."
Syntax:
for variable in sequence:
# code to repeat
The variable takes the value of each item in the sequence, one at a time, each time through the loop.
range() Functionrange() generates a sequence of numbers without you having to list them all.
range(5) — five numbers starting from 0:
for i in range(5):
print(i)
0
1
2
3
4
range(1, 11) — numbers from 1 up to (but not including) 11:
for i in range(1, 11):
print(i)
1
2
3
4
5
6
7
8
9
10
range(0, 10, 2) — even numbers, stepping by 2:
for i in range(0, 10, 2):
print(i)
0
2
4
6
8
The three arguments are:
range(start, stop, step). Stop is always excluded.
range() isn't the only sequence you can loop over. Any list works:
fruits = ["apple", "banana", "mango", "grape"]
for fruit in fruits:
print(f"I love {fruit}s!")
Output:
I love apples!
I love bananas!
I love mangos!
I love grapes!
The loop variable fruit automatically becomes each item in fruits, one at a time.
while Loop: Repeat While a Condition Is TrueA for loop is great when you know how many times to repeat. A while loop is for when you want to keep going as long as a condition holds.
Syntax:
while condition:
# code to repeat
Python checks the condition before each iteration. When it becomes False, the loop stops.
Simple counter example:
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
print("Done!")
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done!
Notice count += 1 inside the loop — this is critical. Without it, count stays at 1 forever and the loop never ends.
# DANGER — do not run this
while True:
print("This will print forever")
This is an infinite loop. It never stops because True is always... true. Your program freezes. If this happens, press Ctrl+C to force-stop it.
The safe pattern: always make sure something inside the loop will eventually make the condition False, or use break to exit.
| Situation | Best Choice |
|---|---|
| You know exactly how many times to repeat | for loop |
| You're iterating over a list, string, or range | for loop |
| You repeat until the user does something | while loop |
| You repeat until a calculation converges | while loop |
| You don't know in advance how many times | while loop |
A useful mental model: for = "do this N times" or "do this for each item"; while = "keep doing this until something changes."
A teacher wants to print the multiplication table for any number a student requests. Without a loop, this means 10 print statements per number — tedious. With a loop, it's elegant.
number = int(input("Enter a number: "))
print(f"\nMultiplication table for {number}:")
for i in range(1, 11):
result = number * i
print(f"{number} × {i} = {result}")
What each part does:
int(input(...)) — reads the user's input and converts to integerrange(1, 11) — generates numbers 1 through 10result = number * i — calculates the product for this rowSample run (user enters 7):
Enter a number: 7
Multiplication table for 7:
7 × 1 = 7
7 × 2 = 14
7 × 3 = 21
7 × 4 = 28
7 × 5 = 35
7 × 6 = 42
7 × 7 = 49
7 × 8 = 56
7 × 9 = 63
7 × 10 = 70
Now something more interactive. The user guesses a secret number. We don't know how many guesses they'll need — it could be 1, it could be 20. A while loop is perfect here.
secret = 42
attempts = 0
while True:
guess = int(input("Guess the number: "))
attempts += 1
if guess == secret:
print(f"Correct! You got it in {attempts} attempts!")
break
elif guess < secret:
print("Too low! Try higher.")
else:
print("Too high! Try lower.")
What each part does:
while True: — loops indefinitely until we explicitly break outattempts += 1 — counts each guess (equivalent to attempts = attempts + 1)if guess == secret: — the winning condition; break exits the loop immediatelyelif guess < secret: — gives a helpful hint without revealing the answerelse: — covers the case where the guess is too highSample run:
Guess the number: 70
Too high! Try lower.
Guess the number: 30
Too low! Try higher.
Guess the number: 50
Too high! Try lower.
Guess the number: 42
Correct! You got it in 4 attempts!
The player gets immediate, useful feedback every round. The loop does the heavy lifting — we never had to predict how many rounds to allow.
for loop when you know the sequence or count in advancewhile loop when you repeat based on a changing conditionrange(start, stop, step) generates number sequences for for loopswhile loops have an exit condition to avoid infinite loopsbreak exits a loop immediately from anywhere inside itNext lesson: Nested loops and loop control — how to manage loops inside loops, and how break and continue give you fine-grained control.
Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises