0% found this document useful (0 votes)
9 views5 pages

For Loop

The document explains the for loop in Python, which is used for iterating over sequences like lists, tuples, and strings. It covers the basic syntax, examples of looping over different iterables, and advanced control features such as break and continue. Additionally, it discusses nested for loops for handling multi-dimensional data structures.

Uploaded by

ammuardra146
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)
9 views5 pages

For Loop

The document explains the for loop in Python, which is used for iterating over sequences like lists, tuples, and strings. It covers the basic syntax, examples of looping over different iterables, and advanced control features such as break and continue. Additionally, it discusses nested for loops for handling multi-dimensional data structures.

Uploaded by

ammuardra146
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

What is a for Loop?

In Python, the for loop is used for iterating over a sequence. A sequence can be a
list, a tuple, a dictionary, a set, a string, or the result of the range() function.
Unlike a while loop that runs as long as a condition is true, a for loop runs for a
specific number of times—once for each item in the sequence. It's often described as
a "for each" loop because it performs an action "for each item in the collection."
Basic Syntax
The fundamental syntax of a for loop is clean and readable:
for variable in iterable:
# This indented block of code (the "loop body")
# will execute once for each item in the 'iterable'.
# Inside the loop, 'variable' will hold the current item
Explanation of Components:
 for: The keyword that starts the loop.
 variable: A temporary variable name you choose. In each iteration, this variable
will hold the current item from the iterable.
 in: The keyword that links the variable to the iterable.
 iterable: The sequence or collection you want to loop through (e.g., a list, a
string).
 :: A colon is required at the end of the for line.
 Indented Block: The code that will be executed for each item in the iterable

 Examples with Different Iterables

1. Looping Over a List


This is the most common use case. The loop will process each element of the list one
by one.
fruits = ["apple", "banana", "cherry", "date"]

print("Our fruit selection:")


for fruit in fruits:
print(f"- {[Link]()}")
Output:
Our fruit selection:
- Apple
- Banana
- Cherry
- Date
How it works: In the first iteration, fruit is "apple". In the second, fruit is "banana",
and so on, until the list is exhausted
2. Looping Over a String
A string is just a sequence of characters, so you can iterate over it directly
message = "Hello!"

for char in message:


print(f"Character: '{char}'")
Output
Character: 'H'
Character: 'e'
Character: 'l'
Character: 'l'
Character: 'o'
Character: '!'
3. Looping with the range() Function
When you need to loop a specific number of times or need a numeric index,
the range() function is your best friend. It generates a sequence of numbers.
a) range(stop): Generates numbers from 0 up to (but not including) stop
# Loop 5 times (for numbers 0, 1, 2, 3, 4)
for i in range(5):
print(f"Looping, iteration number {i}")
Output
Looping, iteration number 0
Looping, iteration number 1
Looping, iteration number 2
Looping, iteration number 3
Looping, iteration number 4
b) range(start, stop): Generates numbers from start up to (but not including) stop
# Loop from 2 to 5 (for numbers 2, 3, 4)

for i in range(2, 6):

print(f"Number: {i}")

Output
Number: 2
Number: 3
Number: 4
Number: 5
c) range(start, stop, step): Generates numbers from start to stop, incrementing by step
# Count down from 10 to 1 by twos

for i in range(10, 0, -2):

print(f"Countdown: {i}")

Output
Countdown: 10
Countdown: 8
Countdown: 6
Countdown: 4
Countdown: 2
4. Looping Over a Dictionary
You can loop over a dictionary's keys, values, or both.
d) Looping over keys (default behaviour):
user_info = {
"name": "Alice",
"age": 30,
"city": "New York"
}
for key in user_info:
print(f"Key: {key}, Value: {user_info[key]}")
b) Looping over values using .values():
for value in user_info.values():
print(f"Value: {value}")
c) Looping over key-value pairs using .items() (most common method):
for key, value in user_info.items():
print(f"The user's {key} is {value}.")
Output:
The user's name is Alice.
The user's age is 30.
The user's city is New York.

Advanced Loop Control (break, continue, else)


Just like while loops, for loops can use break, continue, and an else block.
 break: Exits the loop immediately.
 continue: Skips the rest of the current iteration and moves to the next item.
 else: Executes only if the loop completes all its iterations without being
terminated by a break.
Example using break and else:
Let's search for a specific user in a list
users = ["Alice", "Bob", "Charlie", "David"]
user_to_find = "Charlie"

for user in users:


print(f"Checking {user}...")
if user == user_to_find:
print(f"Found {user_to_find}!")
break # Stop searching once found
else:
# This block only runs if the loop finishes without a 'break'
print(f"{user_to_find} was not in the list.")
Output:
Checking Alice...
Checking Bob...
Checking Charlie...
Found Charlie!

Nested for Loops


You can place a for loop inside another one. This is useful for working with 2D data
structures, like a grid or a list of lists.
Example: Printing a coordinate grid
# Loop through rows (0, 1, 2)
for x in range(3):
# For each row, loop through columns (0, 1)
for y in range(2):
print(f"({x}, {y})")
Output
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)

You might also like