E-book on Loops in Python

E-Book: Loops in Python

Loops in Python – A Compact E-Book

From first for loop to confident patterns and mini-projects – a practical guide for students, coders and future AI-builders.

🧠 Beginner–Friendly
⚙️ Core Python Concept
📜 Study & Teaching Resource

1. Why Loops Matter

In Python, a loop is the way we tell the computer: “Repeat this block of work again and again until a condition says stop.”

Any repetitive task – printing numbers, calculating totals, scanning files, training ML models – becomes elegant and short with loops. Without loops, most real-world programs would be painfully long and almost impossible to maintain.

Think of loops like the rhythm in a song – the same beat repeating, while the melody (your logic) dances on top of it.

2. Types of Loops in Python

Python mainly gives you two everyday loop tools:

  • for loop – best when you know how many times to repeat, or when you’re iterating over a sequence (list, string, range, etc.).
  • while loop – best when you want to repeat until a condition changes, even if you don’t know in advance how many steps that will take.
for = countable repetition while = condition-based repetition both = backbone of logic

3. The for Loop

3.1 Basic Syntax

for variable in sequence:
    # repeat this block
    # for each item in sequence
      print(variable)

3.2 Example: Print Numbers 1 to 5

for i in range(1, 6):
    print(i)

This will output:

1
2
3
4
5

3.3 Looping Through a List

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print("I like", fruit)

Output:

I like apple
I like banana
I like mango

4. The range() Helper

range() is a special built-in that generates a sequence of numbers, usually used with for loops.

4.1 Forms of range()

  • range(stop) → from 0 to stop - 1
  • range(start, stop) → from start to stop - 1
  • range(start, stop, step) → jump by step

4.2 Examples

# 0 to 4
for i in range(5):
    print(i)

# 1 to 5
for i in range(1, 6):
    print(i)

# Even numbers 2, 4, 6, 8, 10
for i in range(2, 11, 2):
    print(i)

5. The while Loop

A while loop repeats as long as its condition remains True.

5.1 Basic Syntax

while condition:
    # block runs while condition is True
      do_something()

5.2 Example: Print 1 to 5

i = 1

while i <= 5:
    print(i)
    i = i + 1  # or i += 1

Flow:

  1. Start with i = 1.
  2. Check i <= 5. If True → run body, then increase i.
  3. When i becomes 6, condition is False → loop stops.
Always ensure something inside the loop will eventually make the condition False. Otherwise, you create an infinite loop.

5.3 Example: Sum of Digits

n = 5384
total = 0

while n > 0:
    digit = n % 10
    total += digit
    n = n // 10

print("Sum of digits:", total)

6. break, continue, and else with Loops

6.1 break – Stop the Loop Early

Use break when you want to jump out of the loop immediately.

for num in range(1, 11):
    if num == 5:
        break  # exits the loop
    print(num)

Output:

1
2
3
4

6.2 continue – Skip to the Next Iteration

for num in range(1, 11):
    if num % 2 == 0:
        continue  # skip even numbers
    print(num)

Output (only odd numbers):

1
3
5
7
9

6.3 else with Loops

Python allows an else block with loops. It runs only if the loop completes normally (not interrupted by break).

for num in range(1, 6):
    print(num)
else:
    print("Loop finished without break.")

7. Nested Loops & Pattern Printing

A nested loop is a loop inside another loop. Commonly used for patterns, matrices, and working with 2D data.

7.1 Star Triangle Pattern

rows = 5

for i in range(1, rows + 1):
    for j in range(i):
        print("*", end=" ")
    print()

Output:

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

7.2 Multiplication Table (1 to 5)

for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i*j:2}", end=" ")
    print()

8. Common Mistakes with Loops

  • Infinite loop: forgetting to update the variable in a while loop.
  • Off-by-one errors: confusion about whether range() includes the end (it does not).
  • Modifying a list while iterating: can lead to skipped elements or unexpected behavior.
  • Wrong indentation: Python is sensitive to indentation; blocks must be aligned consistently.
Traditional discipline + modern debugging mindset = safe loops. Always mentally trace a few iterations and ask: “Will this loop definitely stop?”

9. Practice Questions (with Answers)

Q1. Write a for loop to print numbers from 10 down to 1.
for i in range(10, 0, -1):
    print(i)
Q2. Use a while loop to print all even numbers from 2 to 20.
i = 2
while i <= 20:
    print(i)
    i += 2
Q3. Given a list nums = [3, 7, 1, 9, 4], write a loop to find the maximum value without using max().
nums = [3, 7, 1, 9, 4]
max_num = nums[0]

for n in nums:
    if n > max_num:
        max_num = n

print("Maximum is:", max_num)
Q4. Write a loop to count how many vowels are there in the string "Python programming".
text = "Python programming"
vowels = "aeiouAEIOU"
count = 0

for ch in text:
    if ch in vowels:
        count += 1

print("Number of vowels:", count)
Q5. Write a nested loop to print this pattern:
1
1 2
1 2 3
1 2 3 4
rows = 4

for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

10. Mini Project Ideas Using Loops

Once you’re comfortable, try these small projects:

  • Number Guessing Game: Computer picks a random number; you use a while loop to keep asking until the guess is right or attempts are over.
  • Menu-Driven Calculator: Use an infinite while True loop for a text menu (Add, Subtract, Multiply, Divide, Exit).
  • To-Do List Manager: Use a loop and a list to add, remove and show tasks.
  • Simple Quiz App: Store questions in a list and use a loop to ask them one by one.

Sample: Tiny Menu-Driven Calculator

while True:
    print("\n1. Add\n2. Subtract\n3. Exit")
    choice = input("Choice: ")

    if choice == "3":
        print("Goodbye!")
        break

    if choice not in ["1", "2"]:
        print("Invalid choice.")
        continue

    a = float(input("Enter first number: "))
    b = float(input("Enter second number: "))

    if choice == "1":
        print("Result:", a + b)
    else:
        print("Result:", a - b)
Scroll to Top