For Loop in Python

A for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or any other iterable object. Unlike a while loop that runs as long as a condition is true, a for loop runs a specific number of times—once for each item in the sequence.

The Syntax

Python

for item in sequence:
    # Code to execute for each item
  1. Python assigns the first value in the sequence to the variable item.
  2. The code block inside the loop executes.
  3. Python assigns the next value in the sequence to item and runs the block again.
  4. This continues until there are no more items in the sequence.

5 Detailed Examples

Here are five examples demonstrating the versatility of for loops in Python, from iterating over basic collections to using built-in helper functions.

1. Iterating Over a List

This is the most standard use of a for loop. It goes through each element in a list one by one in the order they appear.

Python

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

for fruit in fruits:
    print(f"I like to eat {fruit}s.")

# Output:
# I like to eat apples.
# I like to eat bananas.
# I like to eat cherrys.

2. Using the range() Function

The range() function generates a sequence of numbers, which is incredibly useful when you want a for loop to run a specific number of times. It can take up to three arguments: range(start, stop, step).

Python

# range(5) generates numbers from 0 up to, but not including, 5
for i in range(5):
    print(f"Iteration {i}")

print("---")

# range(2, 10, 2) starts at 2, stops before 10, and steps by 2
for even_number in range(2, 10, 2):
    print(even_number)

# Output:
# Iteration 0
# Iteration 1
# Iteration 2
# Iteration 3
# Iteration 4
# ---
# 2
# 4
# 6
# 8

3. Iterating Over a String

In Python, strings are just sequences of characters. A for loop will iterate through a string character by character.

Python

word = "Python"

for letter in word:
    # end="-" prevents print from starting a new line every time
    print(letter.upper(), end="-")

# Output:
# P-Y-T-H-O-N-

4. Using enumerate() to Get the Index

Often, you need both the value of the item and its position (index) in the sequence. The enumerate() function provides a clean way to get both simultaneously without having to manually set up a counter variable.

Python

top_movies = ["The Matrix", "Inception", "Interstellar"]

# enumerate() returns a tuple (index, value) for each iteration
for rank, movie in enumerate(top_movies, start=1):
    print(f"Rank {rank}: {movie}")

# Output:
# Rank 1: The Matrix
# Rank 2: Inception
# Rank 3: Interstellar

5. Iterating Over a Dictionary

Dictionaries hold key-value pairs. By default, iterating over a dictionary yields its keys. However, using the .items() method allows you to loop through both the keys and the values at the same time.

Python

student_grades = {
    "Alice": "A",
    "Bob": "C+",
    "Charlie": "B"
}

# .items() unpacks both the key (name) and the value (grade)
for name, grade in student_grades.items():
    print(f"Student {name} scored a {grade}.")

# Output:
# Student Alice scored a A.
# Student Bob scored a C+.
# Student Charlie scored a B.

Here is a collection of 20 Python while loop examples, structured from fundamental concepts to more practical applications. You can use these to gradually build your students’ understanding of iteration, condition checking, and loop control.

Part 1: Basic Counting and Iteration

These examples establish the core mechanics of a while loop: initialization, condition, and increment/decrement.

1. Simple Counter (1 to 5)

Demonstrates the most basic form of a loop.

Python

i = 1
while i <= 5:
    print("Count:", i)
    i += 1  # Always remind students to increment!

2. Countdown (5 to 1)

Shows how to decrement a value until it reaches a base condition.

Python

countdown = 5
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Blastoff!")

3. Printing Even Numbers

Introduces stepping by values other than 1.

Python

num = 2
while num <= 10:
    print(num)
    num += 2  # Increment by 2

4. Printing Odd Numbers

Similar to the above, but starts at a different initial value.

Python

num = 1
while num <= 10:
    print(num)
    num += 2

5. Sum of First N Natural Numbers

Introduces the concept of an accumulator variable.

Python

n = 5
total = 0
i = 1
while i <= n:
    total += i  # Accumulate the sum
    i += 1
print("Sum is:", total)

Part 2: Mathematical Operations

These loops show how iteration is used to solve standard mathematical problems.

6. Factorial of a Number

A classic algorithmic example for freshers.

Python

num = 5
factorial = 1
while num > 0:
    factorial *= num
    num -= 1
print("Factorial is:", factorial)

7. Multiplication Table

Useful for showing how loops can generate structured data.

Python

multiplier = 7
i = 1
while i <= 10:
    print(f"{multiplier} x {i} = {multiplier * i}")
    i += 1

8. Sum of Digits

Teaches students how to use modulo (%) and floor division (//) to break down numbers.

Python

number = 456
digit_sum = 0
while number > 0:
    digit_sum += number % 10  # Extract last digit
    number //= 10             # Remove last digit
print("Sum of digits:", digit_sum)

9. Reverse a Number

Builds on the previous logic to construct a new integer.

Python

number = 1234
reversed_num = 0
while number > 0:
    remainder = number % 10
    reversed_num = (reversed_num * 10) + remainder
    number //= 10
print("Reversed:", reversed_num)

10. Generating the Fibonacci Sequence

Great for explaining how variables can hand off values to each other.

Python

n_terms = 5
a, b = 0, 1
count = 0
while count < n_terms:
    print(a, end=" ")
    a, b = b, a + b  # Update values simultaneously 
    count += 1

Part 3: Loop Control Statements

Teaching break and continue gives students finer control over execution flow.

11. Using break to Exit Early

Shows how to stop a loop before the main condition evaluates to False.

Python

i = 1
while i <= 10:
    if i == 5:
        print("Breaking the loop at 5")
        break
    print(i)
    i += 1

12. Using continue to Skip an Iteration

Shows how to bypass specific conditions without stopping the whole loop.

Python

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue  # Skips printing '3'
    print(i)

13. The “Do-While” Simulation (Infinite Loop with Break)

Python doesn’t have a native do-while loop, so this is the standard workaround.

Python

while True:
    user_input = "exit"  # Hardcoded for example, usually input()
    print("Running...")
    if user_input == "exit":
        break

Part 4: Data Structures (Lists and Strings)

While for loops are usually better for iterables in Python, doing it with while teaches students about index bounds.

14. Iterating Through a List

Teaches the relationship between loop counters and array/list indices.

Python

fruits = ["apple", "banana", "cherry"]
index = 0
while index < len(fruits):
    print(fruits[index])
    index += 1

15. Iterating Through a String

Treats strings as arrays of characters.

Python

text = "Python"
index = 0
while index < len(text):
    print(text[index])
    index += 1

16. Emptying a List Using pop()

A practical data-processing pattern.

Python

tasks = ["Task 1", "Task 2", "Task 3"]
while tasks:  # Loops as long as the list is not empty
    current = tasks.pop(0)
    print("Processing:", current)

17. Removing All Instances of a Specific Value

Shows a clean way to sanitize a list.

Python

numbers = [1, 2, 3, 2, 4, 2, 5]
while 2 in numbers:
    numbers.remove(2)
print("Cleaned list:", numbers)

Part 5: Logic and Patterns

More advanced loops that require tracking state or multiple variables.

18. Linear Search with a While Loop

A foundational algorithm for computer science students.

Python

data = [10, 20, 30, 40, 50]
target = 30
index = 0
found = False

while index < len(data) and not found:
    if data[index] == target:
        found = True
        print(f"Found {target} at index {index}")
    index += 1

19. Finding the Greatest Common Divisor (Euclidean Algorithm)

A neat, efficient algorithm that relies heavily on a while loop.

Python

a = 48
b = 18
while b != 0:
    temp = b
    b = a % b
    a = temp
print("GCD is:", a)

20. Printing a Right-Angled Triangle Pattern

Nested loops (or string multiplication) to build visual patterns.

Python

rows = 5
i = 1
while i <= rows:
    j = 1
    while j <= i:
        print("*", end=" ")
        j += 1
    print("")  # Move to the next line
    i += 1

Similar Posts

  • Mathematical Functions

    1. abs() Syntax: abs(x)Description: Returns the absolute value (non-negative value) of a number. Examples: python # 1. Basic negative numbers print(abs(-10)) # 10 # 2. Positive numbers remain unchanged print(abs(5.5)) # 5.5 # 3. Floating point negative numbers print(abs(-3.14)) # 3.14 # 4. Zero remains zero print(abs(0)) # 0 # 5. Complex numbers (returns magnitude) print(abs(3 +…

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Positional-Only Arguments in Python

    Positional-Only Arguments in Python Positional-only arguments are function parameters that must be passed by position (order) and cannot be passed by keyword name. Syntax Use the / symbol in the function definition to indicate that all parameters before it are positional-only: python def function_name(param1, param2, /, param3, param4): # function body Simple Examples Example 1: Basic Positional-Only Arguments python def calculate_area(length,…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

Leave a Reply

Your email address will not be published. Required fields are marked *