Skip to main content
Python for Beginners
CHAPTER 08 Beginner

Loops in Python

Updated: May 17, 2026
20 min read

# Loops in Python

Welcome to Chapter 8! Loops let you repeat code automatically. Instead of writing the same code 100 times, a loop does it for you.

---

1. Learning Objectives

  • Use for and while loops.
  • Control loops with break, continue, and pass.
  • Use range() for numeric sequences.
  • Write nested loops.
  • Build a number guessing game.

---

2. The for Loop

```python id="py8_ex1" fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I love {fruit}!")

# Iterating over a string for char in "Python": print(char, end=" ") # P y t h o n

1234
---

## 3. The range() Function

python id="py8_ex2" # range(stop) for i in range(5): print(i, end=" ") # 0 1 2 3 4

print()

# range(start, stop) for i in range(1, 6): print(i, end=" ") # 1 2 3 4 5

print()

# range(start, stop, step) for i in range(0, 20, 3): print(i, end=" ") # 0 3 6 9 12 15 18

print()

# Counting backwards for i in range(5, 0, -1): print(i, end=" ") # 5 4 3 2 1

1234
---

## 4. The while Loop

python id="py8_ex3" count = 1 while count <= 5: print(f"Count: {count}") count += 1

# Sentinel loop password = "" while password != "python123": password = input("Enter password: ") print("Access granted! ✅")

1234
---

## 5. break, continue, and pass

python id="py8_ex4" # break — exit the loop immediately for i in range(10): if i == 5: break print(i, end=" ") # 0 1 2 3 4

print()

# continue — skip current iteration for i in range(10): if i % 2 == 0: continue print(i, end=" ") # 1 3 5 7 9

print()

# pass — placeholder (do nothing) for i in range(5): pass # TODO: implement later

1234
---

## 6. for-else and while-else

python id="py8_ex5" # else block runs when loop completes WITHOUT break for i in range(5): print(i, end=" ") else: print("\nLoop completed!")

# With break — else doesn't run for i in range(5): if i == 3: break else: print("This won't print")

# Practical: search example numbers = [1, 3, 5, 7, 9] target = 4

for num in numbers: if num == target: print(f"Found {target}!") break else: print(f"{target} not found in list")

1234
---

## 7. Nested Loops

python id="py8_ex6" # Multiplication table for i in range(1, 6): for j in range(1, 6): print(f"{i*j:4}", end="") print()

# Pattern: Right triangle for i in range(1, 6): print("* " * i)

1
**Output:**

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

  • * *
  • * *
  • * * *
  • * * * *

123456
---

## 8. Practical Examples

### Fibonacci Sequence

python id="py8ex7" n = 10 a, b = 0, 1 print("Fibonacci Sequence:") for in range(n): print(a, end=" ") a, b = b, a + b # 0 1 1 2 3 5 8 13 21 34

12
### Sum of Digits

python id="py8_ex8" number = 12345 total = 0 for digit in str(number): total += int(digit) print(f"Sum of digits of {number}: {total}") # 15

1234
---

## 9. Mini Project: Number Guessing Game

python id="py8project" import random

print("=" * 40) print(" 🎯 NUMBER GUESSING GAME") print("=" * 40)

secret = random.randint(1, 100) attempts = 0 maxattempts = 7

print(f"Guess a number between 1 and 100") print(f"You have {maxattempts} attempts\n")

while attempts < maxattempts: guess = int(input(f"Attempt {attempts + 1}: ")) attempts += 1 if guess == secret: print(f"\n🎉 Correct! You got it in {attempts} attempts!") break elif guess < secret: print("📈 Too low!") else: print("📉 Too high!") else: print(f"\n😞 Game Over! The number was {secret}") ``

---

10. Common Mistakes

  1. 1. Infinite loops: Forgetting to update the loop variable in while.
  1. 2. Off-by-one errors: range(5) gives 0-4, not 1-5.
  1. 3. Modifying list while iterating: Can cause unexpected behavior.
  1. 4. Using break when continue is needed and vice versa.

---

11. MCQs with Answers

Q1: range(3) produces: A) 1,2,3 B) 0,1,2 C) 0,1,2,3 D) 1,2 Answer: B

Q2: Which exits the loop immediately? A) continue B) pass C) break D) stop Answer: C

Q3: continue does: A) Exits loop B) Skips to next iteration C) Does nothing D) Restarts loop Answer: B

Q4: When does for-else execute? A) Always B) On error C) When break is used D) When loop completes without break Answer: D

Q5: range(2, 10, 3) produces: A) 2,5,8 B) 2,4,6,8 C) 3,6,9 D) 2,3,4 Answer: A

Q6: What does pass do? A) Exits B) Skips C) Nothing D) Errors Answer: C

Q7: To loop backwards: A) range(5,0) B) range(5,0,-1) C) range(-5,0) D) reverse(range(5)) Answer: B

Q8: in for in range(5) means: A) Error B) Variable unused C) Private D) Constant Answer: B

Q9: Infinite loop: A) while True B) while False C) for True D) loop forever Answer: A

Q10: enumerate() returns: A) Only values B) Only indices C) Index-value pairs D) Sorted values Answer: C

---

12. Interview Questions

  1. 1. Difference between for and while? for iterates over sequences; while loops based on a condition.
  1. 2. What is the for-else construct? The else block executes when the loop completes without hitting break.
  1. 3. How to avoid infinite loops? Ensure the while condition eventually becomes False.
  1. 4. What is enumerate() and why use it? Returns index-value pairs; avoids manual index tracking.
  1. 5. How to iterate over multiple lists simultaneously? Use zip().

---

13. Summary

  • for iterates over sequences; while repeats based on conditions.
  • range() generates numeric sequences.
  • break exits, continue skips, pass does nothing.
  • for-else runs else when loop completes without break.
  • Use enumerate() for index+value, zip()` for parallel iteration.

---

14. Next Chapter Recommendation

In Chapter 9: Python Strings, you'll master string creation, indexing, slicing, methods, and formatting! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·