Loops
Repeating code with for and while loops, range(), nested loops for patterns, and the break / continue / pass / loop-else control-flow tools.
So far, every program you've written runs each line exactly once. But real programs often need to repeat an action — printing every item in a list, checking every student's marks, or asking a user to guess a number until they get it right. That's what loops are for.
1. What are Loops?
What is it?
A loop is a block of code that repeats itself as long as a certain condition holds true (or for a fixed number of times).
Definition: A loop is a programming structure that repeats a block of code multiple times without rewriting it manually.
Why do we use it?
Without loops, printing numbers 1 to 100 would mean writing 100 separate print() statements. Loops let you write the instruction once and tell Python how many times (or under what condition) to repeat it.
How does it work?
Python offers two main loop types:
- `for` loop — repeats a fixed number of times, or once for each item in a sequence (like a list or range of numbers).
- `while` loop — repeats as long as a condition stays
True, without necessarily knowing in advance how many times.
2. The for Loop
Syntax
pythonfor variable in sequence: # code to repeat
Simple Example
pythonfor i in range(5): print(i)
Output:
0
1
2
3
4Explanation of the Code
range(5)generates the sequence of numbers0, 1, 2, 3, 4(starting at 0, stopping before 5).- The loop runs once for each value, storing it in
ieach time. print(i)runs 5 times total, once per value.
Real-World Example
Printing every student's name from a list of registered students, or processing every order in today's sales list.
pythonstudents = ["Riya", "Aman", "Zara"] for student in students: print("Hello,", student)
Output:
Hello, Riya
Hello, Aman
Hello, ZaraCommon Mistakes
- Forgetting that
range(5)starts at0and stops before5(so it gives 5 values: 0–4, not 1–5). - Forgetting the colon
:at the end of theforline.
Important Points
forloops are best when you know (or can generate) the sequence you want to loop over.- You can loop directly over lists, strings, and other collections — not just numbers.
Practice
- Write a
forloop that prints numbers from 1 to 10. - Write a
forloop that prints each letter of the word"PYTHON"on a separate line.
3. Understanding range()
What is it?
range() generates a sequence of numbers, most commonly used to control how many times a for loop runs.
Syntax
pythonrange(stop) # 0 to stop-1 range(start, stop) # start to stop-1 range(start, stop, step) # start to stop-1, jumping by step
Simple Examples
pythonprint(list(range(5))) # [0, 1, 2, 3, 4] print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7] print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8] print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Explanation
range(5)starts at 0 by default and stops before the given number.- Adding a
startvalue changes where counting begins. - The third value,
step, controls the jump size — and can be negative to count downward.
Common Mistakes
- Expecting
range(1, 10)to include10— it stops at9. - Forgetting a negative
stepwhen trying to count backward —range(10, 0)alone produces an empty sequence; you needrange(10, 0, -1).
Important Points
range()doesn't create a full list in memory by default — it's a memory-efficient sequence generator. Wrap it inlist()only when you want to see/print all values at once.
Practice
- Use
range()to print all even numbers from 2 to 20. - Use
range()to print numbers from 10 down to 1.
4. The while Loop
Syntax
pythonwhile condition: # code to repeat while condition is True
Simple Example
pythoncount = 1 while count <= 5: print(count) count += 1
Output:
1
2
3
4
5Explanation of the Code
- The loop keeps running as long as
count <= 5isTrue. count += 1increasescountby 1 each time — this is essential; without it, the condition would never becomeFalse, causing an infinite loop.
Real-World Example — Login Attempts
pythoncorrect_password = "python123" attempts = 0 while attempts < 3: entered = input("Enter password: ") if entered == correct_password: print("Login successful") break attempts += 1 print("Wrong password. Try again.") else: print("Too many failed attempts. Account locked.")
Common Mistakes
- Forgetting to update the loop variable, causing an infinite loop (the program never stops).
- Using
whilewhen aforloop would be simpler (e.g., looping a fixed, known number of times).
Important Points
- Use
whilewhen the number of repetitions isn't known in advance and depends on a changing condition. - Always make sure something inside the loop eventually makes the condition
False.
Practice
- Write a
whileloop that prints numbers from 10 down to 1. - Write a
whileloop that keeps asking the user to enter a positive number until they do.
Comparison Table — for vs while
for Loop | while Loop | |
|---|---|---|
| Best for | Known number of repetitions, or looping over a sequence | Repeating until a condition becomes False |
| Risk of infinite loop | Low | Higher (if condition never changes) |
| Common use | Iterating over lists, ranges, strings | User input validation, game loops |
5. Nested Loops
What is it?
A loop placed inside another loop — the inner loop completes fully for each single pass of the outer loop.
Simple Example — Multiplication Table
pythonfor i in range(1, 4): for j in range(1, 4): print(i, "x", j, "=", i * j) print("---")
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---Explanation of the Code
- The outer loop runs 3 times (
i = 1, 2, 3). - For each value of
i, the inner loop runs completely (j = 1, 2, 3). - This is why nested loops are perfect for grids, tables, and patterns.
Real-World Example — Star Pattern
pythonrows = 5 for i in range(1, rows + 1): print("*" * i)
Output:
*
**
***
****
*****Real-World Example — Number Pattern
pythonrows = 4 for i in range(1, rows + 1): for j in range(1, i + 1): print(j, end=" ") print()
Output:
1
1 2
1 2 3
1 2 3 4Common Mistakes
- Confusing which loop variable belongs to the outer vs inner loop.
- Forgetting
end=" "when you want output on the same line instead of a new line each time.
Important Points
- The total number of iterations in a nested loop is roughly
outer_iterations x inner_iterations. - Nested loops are the standard technique for pattern printing and grid-like problems (a very common interview/exam topic).
Practice
- Print a pyramid pattern of stars with 6 rows.
- Print a multiplication table for numbers 1 to 5.
6. break
What is it?
break immediately exits the loop entirely, skipping any remaining iterations.
Simple Example
pythonfor i in range(1, 10): if i == 5: break print(i)
Output:
1
2
3
4Explanation
- As soon as
ibecomes5,breakstops the loop completely —5is never printed, and neither are6,7,8,9.
Real-World Example
Searching a list for a specific value and stopping as soon as it's found, instead of wastefully checking the rest.
pythonnumbers = [4, 8, 15, 16, 23, 42] target = 15 for num in numbers: if num == target: print("Found it!") break
Common Mistakes
- Expecting
breakto only exit the current inner loop when nested — it only exits the innermost loop it's directly inside.
Important Points
breakcompletely ends the nearest enclosing loop.- Commonly paired with a search condition.
7. continue
What is it?
continue skips the rest of the current iteration and moves directly to the next one — the loop keeps running, it just skips one round.
Simple Example
pythonfor i in range(1, 6): if i == 3: continue print(i)
Output:
1
2
4
5Explanation
- When
i == 3,continueskips theprint(i)line for that round only, then moves on toi = 4. - Unlike
break, the loop doesn't stop — it just skips that one iteration.
Real-World Example
Processing a list of numbers but skipping negative values:
pythonnumbers = [4, -2, 7, -8, 10] for num in numbers: if num < 0: continue print(num)
Common Mistakes
- Confusing
continue(skip this round) withbreak(stop everything) — this is a very common beginner mix-up.
Important Points
continueskips only the current iteration, not the whole loop.
8. pass
What is it?
pass does absolutely nothing — it's a placeholder used when Python syntax requires a statement, but you don't want any action to happen (yet).
Simple Example
pythonfor i in range(5): if i == 3: pass # TODO: handle this case later print(i)
Output:
0
1
2
3
4Real-World Example
Used often while planning out code structure — you write the if condition first and use pass as a placeholder until you decide what should actually happen there.
Important Points
passis different fromcontinue—passdoes nothing and execution continues normally to the next line in the same block;continueactively skips to the next loop iteration.
Comparison Table — break vs continue vs pass
| Keyword | Effect |
|---|---|
break | Exits the loop completely |
continue | Skips current iteration, continues looping |
pass | Does nothing — just a placeholder |
9. Loop else
What is it?
Both for and while loops in Python can have an else block — an unusual but useful feature. The else block runs only if the loop completed normally, without hitting a `break`.
Simple Example
pythonfor i in range(1, 5): print(i) else: print("Loop finished without break")
Output:
1
2
3
4
Loop finished without breakExample Where else is Skipped
pythonfor i in range(1, 5): if i == 3: break print(i) else: print("This will NOT print")
Output:
1
2Explanation
- In the second example,
breaktriggers wheni == 3, so the loop exits early — and because it didn't finish naturally, theelseblock is skipped entirely.
Real-World Example
Checking whether a number is prime — if no divisor is found through the entire loop (no break), the else block can confirm "this number is prime."
pythonnumber = 7 is_prime = True for i in range(2, number): if number % i == 0: is_prime = False break else: print(number, "is prime")
Common Mistakes
- Assuming loop-
elsebehaves like theelsein anifstatement — it's tied to whetherbreakoccurred, not a simple opposite condition.
Important Points
- Loop-
elseruns when the loop finishes without abreak. - It's a lesser-known but genuinely useful Python feature, especially for search-and-confirm logic.
Common Beginner Mistakes — Summary for This Section
- Off-by-one errors with
range()(forgetting it stops before the given number). - Forgetting to update the loop variable in a
whileloop, causing an infinite loop. - Mixing up
breakandcontinue. - Confusing which loop a nested
break/continueaffects (it's always the innermost loop).
Cheat Sheet — Loops
python# for loop for i in range(start, stop, step): ... # while loop while condition: ... # break / continue / pass break # exit loop entirely continue # skip to next iteration pass # do nothing (placeholder) # loop-else for i in range(5): ... else: ... # runs only if no break occurred
Mini Project: Number Guessing Game
Objective
Build a game where the computer picks a random number, and the user has to guess it within a limited number of attempts, using both conditionals and loops together.
Requirements
- Generate a random number between 1 and 100.
- Let the user guess repeatedly.
- Give hints: "Too High" or "Too Low."
- Limit the number of attempts (e.g., 7 tries).
- Announce win/loss at the end.
Concepts Used
Variables, input/output, type conversion, if-elif-else, while loop, break, the random module.
Step-by-Step Approach
- Import the
randommodule and generate a secret number. - Set a counter for the number of attempts allowed.
- Use a
whileloop to keep asking for guesses while attempts remain. - Compare the guess to the secret number and give feedback.
- Use
breakto exit immediately on a correct guess. - If the loop finishes without a correct guess, reveal the number.
Complete Code
pythonimport random secret_number = random.randint(1, 100) max_attempts = 7 attempts_used = 0 print("I'm thinking of a number between 1 and 100.") print(f"You have {max_attempts} attempts to guess it.") while attempts_used < max_attempts: guess = int(input("Enter your guess: ")) attempts_used += 1 if guess == secret_number: print(f"Correct! You guessed it in {attempts_used} attempts.") break elif guess < secret_number: print("Too Low!") else: print("Too High!") remaining = max_attempts - attempts_used if remaining > 0: print(f"Attempts remaining: {remaining}") else: print(f"Out of attempts! The number was {secret_number}.")
Code Explanation
random.randint(1, 100)picks a random whole number between 1 and 100 (inclusive on both ends).- The
whileloop keeps running as long as attempts remain. breakends the game immediately on a correct guess.- The loop's
elseblock only runs if thewhileloop finishes without abreak— meaning the player ran out of attempts without guessing correctly. This is a perfect real use case for loop-else.
Sample Output
I'm thinking of a number between 1 and 100.
You have 7 attempts to guess it.
Enter your guess: 50
Too Low!
Attempts remaining: 6
Enter your guess: 75
Too High!
Attempts remaining: 5
Enter your guess: 62
Correct! You guessed it in 3 attempts.Possible Improvements
- Let the user choose the difficulty (number range and attempt count).
- Track and display the best (fewest-attempts) score across multiple games.
- Ask "Play again?" and loop the entire game.
Challenge Task
Modify the game so it also tells the player how "close" their guess was (e.g., "Very close!" if within 5 of the answer).
Interview Questions
Q1. What is the difference between `break` and `continue`? Answer: break exits the loop entirely. continue skips only the current iteration and moves on to the next one, without stopping the loop.
Q2. What does the `else` block attached to a loop do? Answer: It runs only if the loop completes all its iterations without hitting a break. If break is triggered, the else block is skipped.
Q3. What's the difference between `for` and `while` loops? Answer: for loops are typically used when the number of iterations is known or you're iterating over a sequence. while loops are used when repetition depends on a condition that may not have a predetermined number of repeats.
Q4. Why can a `while` loop become infinite? Answer: If the condition being checked never becomes False — usually because the loop forgets to update the variable involved in the condition.
Q5. What does `range(1, 10, 2)` produce? Answer: 1, 3, 5, 7, 9 — starting at 1, stepping by 2, stopping before 10.
Practice Questions
Beginner
- Print all numbers from 1 to 20 using a
forloop. - Print all even numbers from 1 to 50 using a
whileloop. - Print the multiplication table of a number entered by the user.
- Use
breakto stop a loop as soon as it finds the number 7 in a list. - Use
continueto print all numbers from 1 to 10 except multiples of 3.
Intermediate
- Print a right-angled triangle pattern of stars using nested loops.
- Write a program to check whether a number is prime using a
forloop and loop-else. - Write a program that calculates the factorial of a number using a
whileloop. - Print the Fibonacci sequence up to 10 terms using a
forloop. - Write a program to reverse the digits of a number using a
whileloop.
Challenge
- Print a diamond star pattern using nested loops.
- Write a program that finds all prime numbers between 1 and 100.
- Build a simple ATM PIN-entry simulator that gives the user 3 attempts using a
whileloop, and locks the account with a message if all attempts fail.