Module 10: Loops in Python
Loops are one of the fundamental concepts in Python programming. They allow you to execute the same block of code repeatedly without writing the same statements again and again.
For example, suppose you want to print numbers from 1 to 100.
Without a loop:
1print(1) 2print(2) 3print(3) 4# ... 5print(100)
This approach is repetitive, difficult to maintain, and impractical for larger tasks.
With a for loop:
1for number in range(1, 101): 2 print(number)
The same task requires only a few lines of code.
Loops are useful for:
- Processing lists and other collections
- Repeating calculations
- Reading user input until a condition is satisfied
- Searching for values
- Generating patterns
- Processing files
- Building menus and interactive programs
- Performing repetitive data-processing tasks
By the end of this module, you will understand Python for loops, while loops, nested loops, range(), enumerate(), zip(), break, continue, pass, loop else, and practical loop-based programs.
What Is a Loop?
A loop repeatedly executes a block of code.
Python provides two primary loop structures:
| Loop | Best suited for |
|---|---|
for | Iterating over an iterable or a known sequence of values |
while | Repeating code while a condition remains true |
A for loop usually processes items one by one:
1for item in collection: 2 print(item)
A while loop continues while its condition evaluates to True:
1while condition: 2 print("Running")
Why Are Loops Important?
Imagine printing "Python" five times.
Without a loop:
1print("Python") 2print("Python") 3print("Python") 4print("Python") 5print("Python")
With a loop:
1for _ in range(5): 2 print("Python")
Output:
1Python 2Python 3Python 4Python 5Python
The loop makes the program shorter and easier to modify.
For example, changing:
1range(5)
to:
1range(1000)
allows the program to repeat the operation 1,000 times without adding hundreds of lines of code.
Understanding Iteration
An iteration is one execution of a loop body.
Consider:
1for number in range(1, 4): 2 print(number)
The loop performs three iterations:
1Iteration 1 → number = 1 2Iteration 2 → number = 2 3Iteration 3 → number = 3
Output:
11 22 33
Understanding iterations makes it easier to reason about loop execution.
The for Loop
The for loop is used to iterate over an iterable.
Common iterables include:
- Lists
- Tuples
- Strings
- Sets
- Dictionaries
- Ranges
- Other iterable objects
Syntax
1for variable in iterable: 2 statement
The loop takes one item from the iterable at a time and assigns it to the loop variable.
Example: Print Numbers
1for number in range(1, 6): 2 print(number)
Output:
11 22 33 44 55
Here, number receives each value produced by range(1, 6).
Iterating Over a String
Strings are iterable, so you can process each character individually.
1word = "Python" 2 3for letter in word: 4 print(letter)
Output:
1P 2y 3t 4h 5o 6n
This is useful when processing individual characters.
Iterating Over a List
1fruits = ["Apple", "Banana", "Orange"] 2 3for fruit in fruits: 4 print(fruit)
Output:
1Apple 2Banana 3Orange
You can also perform an operation for every item:
1prices = [100, 250, 75] 2 3for price in prices: 4 print(f"Price: ₹{price}")
Output:
1Price: ₹100 2Price: ₹250 3Price: ₹75
Iterating Over a Tuple
1coordinates = (10, 20, 30) 2 3for value in coordinates: 4 print(value)
Output:
110 220 330
Iterating Over a Set
1languages = {"Python", "Java", "C++"} 2 3for language in languages: 4 print(language)
The order of elements in a set should not be relied upon.
Iterating Over a Dictionary
When you iterate directly over a dictionary, Python gives you its keys.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "course": "Python" 5} 6 7for key in student: 8 print(key)
Output:
1name 2age 3course
To access both keys and values, use .items():
1for key, value in student.items(): 2 print(f"{key}: {value}")
Output:
1name: Ankit 2age: 22 3course: Python
The while Loop
A while loop repeatedly executes a block of code as long as its condition is True.
Syntax
1while condition: 2 statement
For example:
1count = 1 2 3while count <= 5: 4 print(count) 5 count += 1
Output:
11 22 33 44 55
The important part is:
1count += 1
It changes the condition variable so that the loop eventually stops.
How a while Loop Works
Consider:
1count = 1 2 3while count <= 3: 4 print(count) 5 count += 1
The execution is:
1count = 1 2↓ 31 <= 3 → True → print 1 4↓ 5count = 2 6↓ 72 <= 3 → True → print 2 8↓ 9count = 3 10↓ 113 <= 3 → True → print 3 12↓ 13count = 4 14↓ 154 <= 3 → False 16↓ 17Loop ends
This demonstrates why the condition and state update are both important in a while loop.
Countdown Example
1number = 5 2 3while number > 0: 4 print(number) 5 number -= 1 6 7print("Blast off!")
Output:
15 24 33 42 51 6Blast off!
Using a while Loop for User Input
A while loop is useful when you don't know how many attempts a user will need.
1password = "" 2 3while password != "python": 4 password = input("Enter password: ") 5 6print("Access granted.")
The loop continues until the user enters the correct password.
For real applications, never store production passwords as plain text. Use a secure authentication system and password hashing.
Infinite Loops
An infinite loop is a loop that never reaches a condition that stops it.
For example:
1while True: 2 print("Running...")
The condition:
1True
never becomes false.
An intentional infinite loop is sometimes useful when combined with break:
1while True: 2 command = input("Enter command: ") 3 4 if command == "exit": 5 break 6 7 print(f"You entered: {command}")
When the user enters exit, the break statement terminates the loop.
for Loop vs while Loop
Choosing the correct loop makes your code easier to understand.
| Situation | Recommended loop |
|---|---|
| Iterate through a list | for |
| Iterate through a string | for |
| Repeat a known number of times | for |
Process values from range() | for |
| Continue until user enters a specific value | while |
| Repeat while a condition remains true | while |
| Unknown number of iterations | Usually while |
Example using for:
1for number in range(10): 2 print(number)
Example using while:
1number = 0 2 3while number < 10: 4 print(number) 5 number += 1
Both can produce similar results, but the for loop is generally clearer when iterating over a known range.
The range() Function
The range() function generates a sequence of integers commonly used with for loops.
It supports three forms:
1range(stop)
1range(start, stop)
1range(start, stop, step)
The stop value is exclusive.
range(stop)
1for number in range(5): 2 print(number)
Output:
10 21 32 43 54
The value 5 is not included.
range(start, stop)
1for number in range(1, 6): 2 print(number)
Output:
11 22 33 44 55
range(start, stop, step)
The step controls how much the value changes after each iteration.
1for number in range(0, 11, 2): 2 print(number)
Output:
10 22 34 46 58 610
Using a Negative Step
A negative step can be used to count backward.
1for number in range(10, 0, -1): 2 print(number)
Output:
110 29 38 47 56 65 74 83 92 101
enumerate()
When iterating over a collection, you sometimes need both the index and the value.
Instead of manually managing a counter, use enumerate().
1fruits = ["Apple", "Banana", "Orange"] 2 3for index, fruit in enumerate(fruits): 4 print(index, fruit)
Output:
10 Apple 21 Banana 32 Orange
You can choose a different starting index:
1for index, fruit in enumerate(fruits, start=1): 2 print(index, fruit)
Output:
11 Apple 22 Banana 33 Orange
Using enumerate() is usually cleaner than:
1index = 0 2 3for fruit in fruits: 4 print(index, fruit) 5 index += 1
zip()
The zip() function allows you to iterate over multiple iterables simultaneously.
1names = ["Ankit", "Rahul", "Aman"] 2marks = [90, 85, 95] 3 4for name, mark in zip(names, marks): 5 print(f"{name}: {mark}")
Output:
1Ankit: 90 2Rahul: 85 3Aman: 95
By default, zip() stops when the shortest iterable is exhausted.
Using zip() With Three Lists
1names = ["Ankit", "Rahul"] 2ages = [22, 21] 3cities = ["Delhi", "Lucknow"] 4 5for name, age, city in zip(names, ages, cities): 6 print(f"{name} | {age} | {city}")
Output:
1Ankit | 22 | Delhi 2Rahul | 21 | Lucknow
This is particularly useful when related data is stored in separate sequences.
The break Statement
The break statement immediately terminates the nearest enclosing loop.
1for number in range(1, 11): 2 if number == 6: 3 break 4 5 print(number)
Output:
11 22 33 44 55
When number becomes 6, Python executes break and exits the loop.
Searching With break
A common use of break is stopping a search when the required value is found.
1numbers = [4, 8, 15, 16, 23, 42] 2target = 23 3 4for number in numbers: 5 if number == target: 6 print("Number found!") 7 break
Output:
1Number found!
The continue Statement
The continue statement skips the remaining code in the current iteration and moves to the next iteration.
1for number in range(1, 6): 2 if number == 3: 3 continue 4 5 print(number)
Output:
11 22 34 45
When number is 3, the print() statement is skipped.
Printing Only Odd Numbers
1for number in range(1, 11): 2 if number % 2 == 0: 3 continue 4 5 print(number)
Output:
11 23 35 47 59
The pass Statement
The pass statement does nothing.
It is useful when Python requires a statement but you intentionally want the block to remain empty.
1for number in range(5): 2 pass 3 4print("Loop completed.")
Output:
1Loop completed.
It is also useful while designing code that will be implemented later:
1def calculate_tax(): 2 pass
Unlike break and continue, pass does not change loop execution.
Loop else
Python allows an else block after a for or while loop.
The loop's else block executes when the loop finishes normally, meaning it was not terminated by break.
Example:
1for number in range(1, 6): 2 print(number) 3else: 4 print("Loop completed normally.")
Output:
11 22 33 44 55 6Loop completed normally.
The difference becomes clearer with break.
1for number in range(1, 6): 2 if number == 3: 3 break 4 5 print(number) 6else: 7 print("Loop completed normally.")
Output:
11 22
The else block does not execute because the loop ended with break.
Practical Example: Prime Number Checker
Loop else can be useful when searching for a factor.
1number = int(input("Enter a number: ")) 2 3if number < 2: 4 print("Not a prime number.") 5else: 6 for divisor in range(2, int(number ** 0.5) + 1): 7 if number % divisor == 0: 8 print("Not a prime number.") 9 break 10 else: 11 print("Prime number.")
The loop searches for a divisor.
If a divisor is found, break runs.
If the loop finishes without finding one, the else block runs.
Nested Loops
A nested loop is a loop inside another loop.
Example:
1for row in range(3): 2 for column in range(4): 3 print("*", end=" ") 4 print()
Output:
1* * * * 2* * * * 3* * * *
The outer loop controls the rows.
The inner loop controls the columns.
How Nested Loops Work
Consider:
1for row in range(2): 2 for column in range(3): 3 print(f"({row}, {column})")
Output:
1(0, 0) 2(0, 1) 3(0, 2) 4(1, 0) 5(1, 1) 6(1, 2)
For every iteration of the outer loop, the entire inner loop executes.
This makes nested loops useful for:
- Tables
- Grids
- Matrices
- Pattern printing
- Comparing combinations of values
Multiplication Grid
1for row in range(1, 4): 2 for column in range(1, 4): 3 print(row * column, end="\t") 4 5 print()
Output:
11 2 3 22 4 6 33 6 9
Pattern Printing
Nested loops are commonly used to generate patterns.
Increasing Triangle
1rows = 5 2 3for row in range(1, rows + 1): 4 for _ in range(row): 5 print("*", end=" ") 6 7 print()
Output:
1* 2* * 3* * * 4* * * * 5* * * * *
Decreasing Triangle
1rows = 5 2 3for row in range(rows, 0, -1): 4 for _ in range(row): 5 print("*", end=" ") 6 7 print()
Output:
1* * * * * 2* * * * 3* * * 4* * 5*
Number Pattern
1rows = 5 2 3for row in range(1, rows + 1): 4 for number in range(1, row + 1): 5 print(number, end=" ") 6 7 print()
Output:
11 21 2 31 2 3 41 2 3 4 51 2 3 4 5
Practice Project: Multiplication Table
Let's build a program that generates the multiplication table for any number.
1number = int(input("Enter a number: ")) 2 3for multiplier in range(1, 11): 4 result = number * multiplier 5 print(f"{number} × {multiplier} = {result}")
Example:
1Enter a number: 7 2 37 × 1 = 7 47 × 2 = 14 57 × 3 = 21 67 × 4 = 28 77 × 5 = 35 87 × 6 = 42 97 × 7 = 49 107 × 8 = 56 117 × 9 = 63 127 × 10 = 70
Practice Project: Sum of Numbers
You can use a loop to calculate the sum of a range of numbers.
1total = 0 2 3for number in range(1, 101): 4 total += number 5 6print("Sum:", total)
Output:
1Sum: 5050
For this particular problem, Python also provides a built-in sum() function:
1total = sum(range(1, 101)) 2print("Sum:", total)
The loop version is still useful for learning how accumulation works.
Practice Project: Factorial
The factorial of a positive integer n is:
1n! = n × (n - 1) × (n - 2) × ... × 1
For example:
15! = 5 × 4 × 3 × 2 × 1 = 120
Python implementation:
1number = int(input("Enter a non-negative integer: ")) 2 3if number < 0: 4 print("Factorial is not defined for negative integers.") 5else: 6 factorial = 1 7 8 for value in range(2, number + 1): 9 factorial *= value 10 11 print("Factorial:", factorial)
Practice Project: Count Vowels
Loops can process every character in a string.
1text = input("Enter text: ") 2 3vowels = "aeiou" 4count = 0 5 6for character in text.lower(): 7 if character in vowels: 8 count += 1 9 10print("Number of vowels:", count)
Example:
1Enter text: Python Programming 2Number of vowels: 4
Practice Project: Find the Largest Number
1numbers = [25, 12, 89, 42, 67] 2 3largest = numbers[0] 4 5for number in numbers[1:]: 6 if number > largest: 7 largest = number 8 9print("Largest:", largest)
Output:
1Largest: 89
Python also has a built-in max() function:
1print(max(numbers))
Learning the loop-based approach is valuable because it demonstrates how comparison and state tracking work internally.
Practice Project: Number Guessing Game
A while loop is useful for interactive programs.
1secret_number = 7 2 3while True: 4 guess = int(input("Guess the number: ")) 5 6 if guess == secret_number: 7 print("Correct! You guessed the number.") 8 break 9 elif guess < secret_number: 10 print("Too low. Try again.") 11 else: 12 print("Too high. Try again.")
This example combines:
whileifelifelsebreak- User input
Practice Project: Menu-Driven Program
Loops and conditional statements can be combined to create a simple menu.
1while True: 2 print("\n1. Say Hello") 3 print("2. Show Python") 4 print("3. Exit") 5 6 choice = input("Choose an option: ").strip() 7 8 if choice == "1": 9 print("Hello!") 10 elif choice == "2": 11 print("Python is powerful.") 12 elif choice == "3": 13 print("Goodbye!") 14 break 15 else: 16 print("Invalid choice.")
The loop keeps displaying the menu until the user chooses 3.
Common Loop Mistakes
Forgetting to Update a while Loop Variable
Incorrect:
1count = 1 2 3while count <= 5: 4 print(count)
The value of count never changes, so the condition remains true.
Correct:
1count = 1 2 3while count <= 5: 4 print(count) 5 count += 1
Using the Wrong range() Endpoint
Remember that the stop value is exclusive.
1for number in range(1, 5): 2 print(number)
Output:
11 22 33 44
It does not print 5.
If you need 5, use:
1range(1, 6)
Incorrect Indentation
Incorrect:
1for number in range(5): 2print(number)
Correct:
1for number in range(5): 2 print(number)
Python uses indentation to identify the loop body.
Using break Outside a Loop
Incorrect:
1break
break can only be used inside a loop.
Confusing continue With break
break:
1Stops the entire loop
continue:
1Skips the current iteration
Example:
1for number in range(1, 6): 2 if number == 3: 3 continue 4 5 print(number)
The loop continues after skipping 3.
Avoid Modifying a Collection While Iterating Over It
Modifying a list while directly iterating over it can produce unexpected behavior.
For example:
1numbers = [1, 2, 3, 4, 5, 6] 2 3for number in numbers: 4 if number % 2 == 0: 5 numbers.remove(number) 6 7print(numbers)
This can skip elements because the list changes while the loop is traversing it.
A safer approach is to create a new list:
1numbers = [1, 2, 3, 4, 5, 6] 2 3odd_numbers = [] 4 5for number in numbers: 6 if number % 2 != 0: 7 odd_numbers.append(number) 8 9print(odd_numbers)
Output:
1[1, 3, 5]
For simple filtering, a list comprehension is even more concise:
1numbers = [1, 2, 3, 4, 5, 6] 2 3odd_numbers = [number for number in numbers if number % 2 != 0] 4 5print(odd_numbers)
Avoid Unnecessary Nested Loops
Nested loops are sometimes necessary, but they can become expensive for large datasets.
For example:
1for i in range(100): 2 for j in range(100): 3 print(i, j)
The inner loop runs for every outer-loop iteration, resulting in 10,000 iterations.
When working with large data, look for ways to reduce unnecessary repeated work or use appropriate data structures and algorithms.
Useful Loop Patterns
Accumulator Pattern
Use a variable to accumulate a result.
1total = 0 2 3for number in [10, 20, 30]: 4 total += number 5 6print(total)
Output:
160
Counter Pattern
Use a variable to count matching items.
1numbers = [10, 15, 20, 25, 30] 2count = 0 3 4for number in numbers: 5 if number % 5 == 0: 6 count += 1 7 8print("Count:", count)
Search Pattern
Use break when the target is found.
1names = ["Ankit", "Rahul", "Aman"] 2 3target = "Rahul" 4 5for name in names: 6 if name == target: 7 print("Found") 8 break
Filtering Pattern
Create a new collection containing only matching values.
1numbers = [1, 2, 3, 4, 5, 6] 2 3even_numbers = [] 4 5for number in numbers: 6 if number % 2 == 0: 7 even_numbers.append(number) 8 9print(even_numbers)
Output:
1[2, 4, 6]
Loop Control Statements Summary
| Statement | Purpose |
|---|---|
break | Immediately exits the loop |
continue | Skips the current iteration |
pass | Does nothing; acts as a placeholder |
Example:
1for number in range(1, 6): 2 if number == 2: 3 continue 4 5 if number == 5: 6 break 7 8 print(number)
Output:
11 23 34
Practice Exercises
Exercise 1: Print Even Numbers
Write a program that prints all even numbers from 1 to 50.
Expected output begins with:
12 24 36 48 510 6...
Exercise 2: Calculate the Sum of Even Numbers
Calculate the sum of all even numbers between 1 and 100.
Exercise 3: Count Digits
Write a program that counts how many digits are present in an integer.
Example:
1Input: 12345 2Output: 5
Exercise 4: Reverse a String
Write a loop that reverses a string without using slicing.
Example:
1Input: Python 2Output: nohtyP
Exercise 5: Find Common Elements
Given two lists, use loops to find values that appear in both lists.
1first = [1, 2, 3, 4, 5] 2second = [3, 4, 5, 6, 7]
Expected result:
1[3, 4, 5]
Exercise 6: Fibonacci Sequence
Write a program that prints the first n Fibonacci numbers.
For example:
10 1 1 2 3 5 8 13 21 34
Exercise 7: Prime Numbers
Write a program that prints all prime numbers between 1 and 100.
Exercise 8: Multiplication Tables
Use nested loops to print multiplication tables from 1 to 10.
Key Takeaways
- Loops allow you to execute code repeatedly.
- Python provides
forandwhileloops. - Use
forwhen iterating over an iterable or a known sequence. - Use
whilewhen repetition depends on a condition. range()generates integer sequences and uses an exclusive stop value.enumerate()provides both indexes and values.zip()allows multiple iterables to be processed together.breakexits a loop immediately.continueskips the current iteration.passacts as a placeholder and performs no operation.- A loop can have an
elseblock that runs when the loop finishes withoutbreak. - Nested loops are useful for grids, tables, patterns, and combinations.
- Always make sure
whileloops have a way to eventually terminate. - Avoid modifying a collection directly while iterating over it unless you fully understand the consequences.
- Built-in functions such as
sum(),max(), andmin()can often replace manual loops in production code, but understanding loops is essential for learning programming.
Loops become significantly more powerful when combined with conditional statements, functions, lists, dictionaries, comprehensions, and exception handling. These concepts form the foundation for building real-world Python applications.