Home » Python for Loops: A Tutorial

Python for Loops: A Tutorial

1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Oracle Java Certification

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or dictionary) and execute a block of code for each item in that sequence.

It’s a versatile and powerful tool for automating repetitive tasks and working with collections of data.

1. Basic Syntax of a for Loop

for variable in sequence:
    # Code to execute for each item in the sequence

variable: A temporary placeholder for each item in the sequence during iteration.
sequence: The collection (list, string, tuple, etc.) over which you are looping.

2. Simple for Loop Example

Let’s start with a simple example where we loop through a list of numbers and print each one.

# Example: Basic for loop over a list
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

# Output:
# 1
# 2
# 3
# 4
# 5

In this example:

The for loop iterates over each element in the numbers list and prints it.

3. Looping Through a String

A string is a sequence of characters, and you can iterate through each character using a for loop.

# Example: For loop over a string
text = "Hello"

for char in text:
    print(char)

# Output:
# H
# e
# l
# l
# o

In this example:

The loop iterates through each character in the string text, printing one character per line.

4. Using range() in for Loops

The range() function generates a sequence of numbers, which is often used in loops for counting or generating index values.

Example: Using range() to Loop Through a Sequence of Numbers

# Example: For loop with range()
for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

In this example:

The range(5) function generates numbers from 0 to 4. The loop iterates over each number in that range.

Example: Using range(start, stop)

You can specify both the start and stop values in range().

# Example: For loop with a start and stop value
for i in range(2, 7):
    print(i)

# Output:
# 2
# 3
# 4
# 5
# 6

Example: Using range(start, stop, step)

You can also specify a step value to control how much the value increments in each iteration.

# Example: For loop with a step value
for i in range(1, 10, 2):
    print(i)

# Output:
# 1
# 3
# 5
# 7
# 9

In this example:

The loop starts at 1 and increments by 2 on each iteration, generating the odd numbers between 1 and 10.

5. Using else with for Loops

You can use an else block with a for loop. The code inside the else block will be executed after the loop finishes, unless the loop is interrupted by a break.

Example: Using else in a Loop

# Example: Using else with for loop
for i in range(5):
    print(i)
else:
    print("Loop finished successfully.")

# Output:
# 0
# 1
# 2
# 3
# 4
# Loop finished successfully.

In this example:

The else block executes after the loop completes.

Example: else Block Skipped with break

If a break statement is encountered in the loop, the else block is skipped.

# Example: Skipping the else block with break
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("This won't be printed because of the break.")

# Output:
# 0
# 1
# 2

In this example:

The loop terminates when i == 3, and the else block is not executed.

6. Using break and continue in for Loops

break: Exits the loop prematurely.
continue: Skips the current iteration and moves to the next one.

Example: Exiting a Loop with break

# Example: Using break in for loop
for i in range(5):
    if i == 3:
        break  # Exit the loop when i equals 3
    print(i)

# Output:
# 0
# 1
# 2

Example: Skipping Iterations with continue

# Example: Using continue in for loop
for i in range(5):
    if i == 2:
        continue  # Skip the current iteration when i equals 2
    print(i)

# Output:
# 0
# 1
# 3
# 4

7. Iterating Over Lists with Indexes

You can use the enumerate() function to loop over a list and access both the index and the value of each element.

Example: Using enumerate() to Access Index and Value

# Example: Using enumerate() in for loop
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry

In this example:

enumerate() returns both the index and the item at that index in the fruits list.

8. Iterating Over Multiple Lists with zip()

The zip() function allows you to iterate over two or more lists (or other sequences) in parallel.

Example: Using zip() to Iterate Over Two Lists

# Example: Using zip() to iterate over two lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

# Output:
# Alice is 25 years old.
# Bob is 30 years old.
# Charlie is 35 years old.

In this example:

zip() pairs the items from the names list with the corresponding items in the ages list.

9. Iterating Over Dictionaries

You can loop through a dictionary’s keys, values, or both using various methods.

Example: Iterating Over Dictionary Keys

# Example: Iterating over dictionary keys
person = {"name": "John", "age": 30, "city": "New York"}

for key in person:
    print(key)

# Output:
# name
# age
# city

Example: Iterating Over Dictionary Values

# Example: Iterating over dictionary values
for value in person.values():
    print(value)

# Output:
# John
# 30
# New York

Example: Iterating Over Dictionary Keys and Values

# Example: Iterating over dictionary keys and values
for key, value in person.items():
    print(f"{key}: {value}")

# Output:
# name: John
# age: 30
# city: New York

In this example:

The items() method returns key-value pairs, allowing you to loop through both the keys and values at the same time.

10. Nested for Loops

A for loop can be nested inside another for loop. This is useful when working with multi-dimensional data structures like matrices or tables.

Example: Nested for Loop to Print a Matrix

# Example: Nested for loop to print a matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()  # Move to the next line after each row

# Output:
# 1 2 3
# 4 5 6
# 7 8 9

In this example:

The outer loop iterates over each row of the matrix, while the inner loop iterates over each element within the row.

11. List Comprehensions in Python

Python provides a concise way to generate lists using a for loop inside square brackets, known as list comprehensions.

Example: List Comprehension to Create a List of Squares

# Example: List comprehension to create a list of squares
squares = [x**2 for x in range(1, 6)]
print(squares)

# Output:
# [1, 4, 9, 16, 25]

In this example:

The list comprehension generates a list of squares for numbers from 1 to 5.

12. Practical Example: Number Guessing Game

Here’s a practical example of using a for loop to create a number guessing game.

# Example: Number guessing game with limited attempts
import random

# Generate a random number between 1 and 10
secret_number = random.randint(1, 10)

# Allow the player to guess 3 times
for attempt in range(3):
    guess = int(input("Guess the number (between 1 and 10): "))
    
    if guess == secret_number:
        print("Congratulations! You guessed the number!")
        break
    else:
        print("Wrong guess.")

else:
    print(f"Sorry, the correct number was {secret_number}.")

In this example:

The player has 3 attempts to guess a random number. If the player guesses correctly, the loop exits using break. If all attempts are used, the else block runs.

Summary

A for loop allows you to iterate over sequences like lists, strings, and ranges.
The break statement is used to exit a loop early, while continue is used to skip the current iteration.
The range() function is useful for generating sequences of numbers in loops.
You can use enumerate() to access both index and value while iterating over a sequence.
zip() allows you to loop through multiple sequences in parallel.
A nested for loop lets you loop over multi-dimensional structures like matrices or lists of lists.

By mastering the for loop in Python, you can efficiently automate repetitive tasks, process sequences, and manipulate data in a structured and organized way.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More