Skip to content
C

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

python
for variable in sequence: # code to repeat

Simple Example

python
for i in range(5): print(i)

Output:

0
1
2
3
4

Explanation of the Code

  • range(5) generates the sequence of numbers 0, 1, 2, 3, 4 (starting at 0, stopping before 5).
  • The loop runs once for each value, storing it in i each 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.

python
students = ["Riya", "Aman", "Zara"] for student in students: print("Hello,", student)

Output:

Hello, Riya
Hello, Aman
Hello, Zara

Common Mistakes

  • Forgetting that range(5) starts at 0 and stops before 5 (so it gives 5 values: 0–4, not 1–5).
  • Forgetting the colon : at the end of the for line.

Important Points

  • for loops 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

  1. Write a for loop that prints numbers from 1 to 10.
  2. Write a for loop 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

python
range(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

python
print(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 start value 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 include 10 — it stops at 9.
  • Forgetting a negative step when trying to count backward — range(10, 0) alone produces an empty sequence; you need range(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 in list() only when you want to see/print all values at once.

Practice

  1. Use range() to print all even numbers from 2 to 20.
  2. Use range() to print numbers from 10 down to 1.

4. The while Loop

Syntax

python
while condition: # code to repeat while condition is True

Simple Example

python
count = 1 while count <= 5: print(count) count += 1

Output:

1
2
3
4
5

Explanation of the Code

  • The loop keeps running as long as count <= 5 is True.
  • count += 1 increases count by 1 each time — this is essential; without it, the condition would never become False, causing an infinite loop.

Real-World Example — Login Attempts

python
correct_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 while when a for loop would be simpler (e.g., looping a fixed, known number of times).

Important Points

  • Use while when 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

  1. Write a while loop that prints numbers from 10 down to 1.
  2. Write a while loop that keeps asking the user to enter a positive number until they do.

Comparison Table — for vs while

for Loopwhile Loop
Best forKnown number of repetitions, or looping over a sequenceRepeating until a condition becomes False
Risk of infinite loopLowHigher (if condition never changes)
Common useIterating over lists, ranges, stringsUser 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

python
for 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

python
rows = 5 for i in range(1, rows + 1): print("*" * i)

Output:

*
**
***
****
*****

Real-World Example — Number Pattern

python
rows = 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 4

Common 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

  1. Print a pyramid pattern of stars with 6 rows.
  2. 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

python
for i in range(1, 10): if i == 5: break print(i)

Output:

1
2
3
4

Explanation

  • As soon as i becomes 5, break stops the loop completely — 5 is never printed, and neither are 6, 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.

python
numbers = [4, 8, 15, 16, 23, 42] target = 15 for num in numbers: if num == target: print("Found it!") break

Common Mistakes

  • Expecting break to only exit the current inner loop when nested — it only exits the innermost loop it's directly inside.

Important Points

  • break completely 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

python
for i in range(1, 6): if i == 3: continue print(i)

Output:

1
2
4
5

Explanation

  • When i == 3, continue skips the print(i) line for that round only, then moves on to i = 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:

python
numbers = [4, -2, 7, -8, 10] for num in numbers: if num < 0: continue print(num)

Common Mistakes

  • Confusing continue (skip this round) with break (stop everything) — this is a very common beginner mix-up.

Important Points

  • continue skips 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

python
for i in range(5): if i == 3: pass # TODO: handle this case later print(i)

Output:

0
1
2
3
4

Real-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

  • pass is different from continuepass does nothing and execution continues normally to the next line in the same block; continue actively skips to the next loop iteration.

Comparison Table — break vs continue vs pass

KeywordEffect
breakExits the loop completely
continueSkips current iteration, continues looping
passDoes 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

python
for i in range(1, 5): print(i) else: print("Loop finished without break")

Output:

1
2
3
4
Loop finished without break

Example Where else is Skipped

python
for i in range(1, 5): if i == 3: break print(i) else: print("This will NOT print")

Output:

1
2

Explanation

  • In the second example, break triggers when i == 3, so the loop exits early — and because it didn't finish naturally, the else block 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."

python
number = 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-else behaves like the else in an if statement — it's tied to whether break occurred, not a simple opposite condition.

Important Points

  • Loop-else runs when the loop finishes without a break.
  • 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 while loop, causing an infinite loop.
  • Mixing up break and continue.
  • Confusing which loop a nested break/continue affects (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

  1. Import the random module and generate a secret number.
  2. Set a counter for the number of attempts allowed.
  3. Use a while loop to keep asking for guesses while attempts remain.
  4. Compare the guess to the secret number and give feedback.
  5. Use break to exit immediately on a correct guess.
  6. If the loop finishes without a correct guess, reveal the number.

Complete Code

python
import 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 while loop keeps running as long as attempts remain.
  • break ends the game immediately on a correct guess.
  • The loop's else block only runs if the while loop finishes without a break — 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

  1. Print all numbers from 1 to 20 using a for loop.
  2. Print all even numbers from 1 to 50 using a while loop.
  3. Print the multiplication table of a number entered by the user.
  4. Use break to stop a loop as soon as it finds the number 7 in a list.
  5. Use continue to print all numbers from 1 to 10 except multiples of 3.

Intermediate

  1. Print a right-angled triangle pattern of stars using nested loops.
  2. Write a program to check whether a number is prime using a for loop and loop-else.
  3. Write a program that calculates the factorial of a number using a while loop.
  4. Print the Fibonacci sequence up to 10 terms using a for loop.
  5. Write a program to reverse the digits of a number using a while loop.

Challenge

  1. Print a diamond star pattern using nested loops.
  2. Write a program that finds all prime numbers between 1 and 100.
  3. Build a simple ATM PIN-entry simulator that gives the user 3 attempts using a while loop, and locks the account with a message if all attempts fail.

Mock Test

  • Loops - Quick Test

    10 questions covering for and while loops, range(), break, continue, pass and loop-else.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems