0% found this document useful (0 votes)
8 views2 pages

Five For Loop Examples

Uploaded by

Tesu Rathia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Five For Loop Examples

Uploaded by

Tesu Rathia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A for loop in programming is a control flow statement for specifying iteration.

It executes a block
of code a specified number of times. It's often used when you know the exact number of times
you want to loop.

1. Basic Iteration over a List


This is the most common use of a for loop. It iterates over each item in a list and performs an
action.
fruits = ["apple", "banana", "cherry"]​
for x in fruits:​
print(x)​

Output:
apple​
banana​
cherry​

This loop goes through the fruits list, assigns each element to the variable x one by one, and
prints it.

2. Looping with the range() Function


The range() function generates a sequence of numbers. It's useful when you need to repeat a
task a specific number of times.
for i in range(5):​
print(i)​

Output:
0​
1​
2​
3​
4​

The range(5) generates numbers from 0 up to (but not including) 5. The loop runs 5 times,
printing i's value each time.

3. Iterating Over a String


A for loop can also iterate over the characters of a string.
for char in "Hello":​
print(char)​

Output:
H​
e​
l​
l​
o​

Here, the loop treats the string "Hello" as a sequence of characters and processes them
individually.

4. Looping Through a Dictionary


You can iterate through a dictionary's keys, values, or both.
person = {"name": "Alice", "age": 30, "city": "New York"}​
for key, value in person.items():​
print(f"{key}: {value}")​

Output:
name: Alice​
age: 30​
city: New York​

The .items() method returns a view of the dictionary's key-value pairs, allowing the loop to
unpack each pair into key and value variables.

5. Nested for Loops


A nested loop is a loop inside another loop. The inner loop completes all its iterations for each
single iteration of the outer loop.
for i in range(3): # Outer loop​
for j in range(2): # Inner loop​
print(f"i = {i}, j = {j}")​

Output:
i = 0, j = 0​
i = 0, j = 1​
i = 1, j = 0​
i = 1, j = 1​
i = 2, j = 0​
i = 2, j = 1​

For each value of i, the inner loop runs completely for both j = 0 and j = 1. This is useful for
tasks like traversing a 2D grid or matrix.

You might also like