What is a loop?#
A loop repeats a block of code. Without loops, printing numbers 1 to 100 would need 100 print() lines. With a loop, it takes three.
Python has two loops:
while- repeats as long as a condition is True.for- repeats for each item in a sequence (next lesson).
Syntax#
while condition:
# body - runs again and again while condition is True
How it works:
- Check the condition.
- If True → run the body, then go back to step 1.
- If False → skip the body and continue after the loop.
The three parts of a counting loop#
Every counting while loop needs three things:
| Part | Example | Purpose |
|---|---|---|
| Initialise | i = 1 |
starting value |
| Condition | while i <= 5: |
when to keep going |
| Update | i += 1 |
move towards the end |
while loop को ऐसे समझें: "जब तक (while) condition सही है, तब तक यह काम करते रहो।"
हर counting loop में तीन चीज़ें ज़रूरी हैं:
- शुरुआत (initialise) - जैसे
i = 1 - शर्त (condition) - जैसे
i <= 5 - बदलाव (update) - जैसे
i += 1
अगर आप तीसरा हिस्सा (update) भूल गए, तो i हमेशा 1 ही रहेगा, condition हमेशा True रहेगी, और loop कभी खत्म नहीं होगा - इसे infinite loop कहते हैं।
Tracing a loop step by step#
total = 0
i = 1
while i <= 4:
total += i
i += 1
print(total)
| Step | i | condition i <= 4 |
total after step |
|---|---|---|---|
| 1 | 1 | True | 1 |
| 2 | 2 | True | 3 |
| 3 | 3 | True | 6 |
| 4 | 4 | True | 10 |
| 5 | 5 | False → stop | 10 |
When a loop gives an unexpected answer, trace it on paper like this table, or add a print(i, total) inside the loop to see each step.
Common patterns#
Accumulator (sum / product)#
Counting digits#
Input validation - repeat until valid#
Menu-driven program#
choice = ""
while choice != "3":
print("1. Deposit 2. Withdraw 3. Exit")
choice = input("Choose: ")
if choice == "1":
print("Depositing...")
elif choice == "2":
print("Withdrawing...")
print("Thank you!")
Infinite loops#
A loop whose condition never becomes False runs forever:
i = 1
while i <= 5:
print(i) # forgot i += 1 -> prints 1 forever
On your computer, press Ctrl + C to stop it. (Our browser editor stops it automatically after a few seconds.)
Sometimes infinite loops are intentional - servers and games run while True: and exit with break:
You'll learn break and continue in detail in a later lesson.
while...else#
A while loop can have an else block. It runs only if the loop ended normally - i.e. the condition became False, not because of break.
Summary#
while condition:repeats the body as long as the condition is True.- Counting loops need: initialise → condition → update.
- Forgetting the update causes an infinite loop (stop with Ctrl + C).
while True:+breakis a common pattern for "repeat until...".while...else: theelseruns only when the loop wasn't broken.