Sunday, January 12, 2025
HomeComputer SciencePython For Loops

Python For Loops

In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code repeatedly for each item in that sequence.

Syntax:

python
for variable in sequence:
# Block of code to execute

Examples:

1. Iterating over a list:

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

2. Iterating over a string:

python
word = "hello"
for letter in word:
print(letter)

Output:

h
e
l
l
o

3. Using range() function:

The range() function is commonly used with for loops to generate a sequence of numbers.

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

Output:

0
1
2
3
4

You can also specify a start, stop, and step in range():

python
for i in range(2, 10, 2):
print(i)

Output:

2
4
6
8

4. Iterating over a dictionary:

python
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(key, ":", value)

Output:

yaml
name : John
age : 30
city : New York

Nested For Loops:

A nested for loop is a loop inside another loop. This is often used to work with multi-dimensional data structures (like lists of lists).

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

Output:

css
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1

break and continue in for loops:

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and moves to the next iteration.
python
for i in range(5):
if i == 3:
break
print(i)

Output:

0
1
2
python
for i in range(5):
if i == 3:
continue
print(i)

Output:

0
1
2
4

For loops are very versatile and can be used for many tasks such as traversing collections, generating sequences, and performing repeated actions.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x