Python Diaries ….. Day 9

For loop

Nishitha Kalathil
5 min readSep 18, 2023

--

Welcome to Day 9 of Python Diaries! Today, we’re exploring the powerful “for” loop. Unlike the “while” loop, which is used for iterating as long as a condition is true, the “for” loop is specifically designed for iterating over sequences or collections of items. This makes it an invaluable tool for tasks that involve processing multiple elements.

What is a For Loop?

A for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. It allows you to perform an action on each item in the sequence, making it an efficient way to process collections of data.

Syntax of a For Loop

Here’s the basic syntax of a for loop:

for item in sequence:
# Code to be executed for each item in the sequence

The loop starts by assigning the first item in the sequence to the variable item. Then, the code block inside the loop is executed. This process continues for each item in the sequence.

Example: Iterating Over a List

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

for fruit in fruits:
print(fruit)

In this example, the for loop iterates over the list of fruits. For each iteration, the current fruit is assigned to the variable fruit, and it is printed.

Using the range() Function

The range() function generates a sequence of numbers, which can be used in a for loop.

for i in range(5):
print(i)

In this example, the for loop iterates over the numbers 0 through 4. The variable i is assigned the current number in each iteration.

Iterating Over a String

A for loop can also be used to iterate over the characters in a string.

for char in "hello":
print(char)

This code will print each character of the string “hello” on a new line.

Using else with a For Loop

As with while loops, you can have an else block associated with a for loop. The code in the else block is executed when the loop completes all iterations without encountering a break.

for i in range(5):
print(i)
else:
print("Loop completed without break")

In this example, the else block will be executed because the loop completes all iterations.

Using break and continue in For Loops

You can use break and continue statements within a for loop to control its behavior.

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

In this example, the loop will exit when i equals 3 due to the break statement.

for i in range(5):
if i == 3:
continue # Skip the rest of the loop and continue with the next iteration
print(i)

In this example, when i equals 3, the continue statement is executed. This skips printing 3 and continues with the next iteration.

Using enumerate() in For Loops

The enumerate() function is used to loop over both the elements and their indices in a sequence.

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

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

output bill be:

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

Using zip() in For Loops

The zip() function is used to iterate over multiple sequences simultaneously.

names = ["John", "Jane", "Bob"]
ages = [30, 25, 35]

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

Using sorted() in For Loops

The sorted() function in Python is used to sort elements in a specific iterable, such as a list, tuple, or string. It returns a new sorted list without modifying the original iterable.

numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]

List comprehensions

List comprehensions are a concise way to create lists in Python. They allow you to generate a new list by applying an expression to each item in an existing iterable (like a list, tuple, or range), optionally including a condition to filter the items.

# Generating a List of Squares

squares = [x**2 for x in range(5)]
# Output: [0, 1, 4, 9, 16]


# Filtering Odd Numbers
odd_numbers = [x for x in range(10) if x % 2 != 0]
# Output: [1, 3, 5, 7, 9]

Nested For Loops

Just like with while loops, you can have nested for loops. This means one for loop can be inside another for loop.

for i in range(3):
for j in range(3):
print(f"({i}, {j})")

The output will be

(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)

Creating patterns

Creating patterns in Python involves using loops to generate a specific arrangement of characters or numbers. Patterns can range from simple shapes to intricate designs. Below are examples of patterns using loops:

Printing a Square Pattern:

size = 5

for i in range(size):
for j in range(size):
print("* ", end="")
print()

output:

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

Printing a Right Triangle Pattern:

size = 5

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

output:

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

These are just a few examples of patterns you can create using loops in Python. With some creativity and experimentation, you can design a wide variety of patterns to suit your needs.

The for loop is an essential tool for iterating over sequences and performing actions on each item. Whether you’re working with lists, strings, or other iterable objects, mastering the for loop is crucial for effective Python programming.

You can access the other topics in this tutorial series right here:

In Day 10, we’ll delve into the concept of functions, which allow you to organize and reuse blocks of code. Keep up the great work! Happy coding!

--

--