for Loop in python
In programming, there are situations where the same block of code needs to run multiple times. Loops help automate this repetition. Python provides three main types of loops: for loops, while loops, and nested loops.
What is a for Loop?
The for loop retrieves each item from a sequence one at a time and executes the specified code block for each iteration.
Syntax
for variable in sequence:
# code block
Key Points
- Used to iterate over a sequence.
- Executes a block of code repeatedly.
-
Commonly used with
.range() - Automatically stops when all items have been processed.
- Reduces the need for repetitive code.
- Supports iteration over strings, lists, tuples, sets, and dictionaries.
Example 1: Print Numbers Using range()
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
Explanation
The function generates numbers from 1 to 5, and the loop prints each number.
range(1, 6)
Example 2: Iterate Through a List
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
Output
Apple
Banana
Mango
Explanation
The loop accesses each item in the list and prints it.
Example 3: Iterate Through a String
for letter in "Python":
print(letter)
Output
P
y
t
h
o
n
Explanation
The loop processes one character at a time from the string "Python".
Common Uses of for Loops
- Processing items in a list.
- Traversing strings.
- Repeating tasks a specific number of times.
- Generating patterns and tables.
- Performing calculations on collections of data.