The for loop is used to iterate over a sequence (list, tuple, string, dictionary,set, range, etc.) or any iterable object.
Comment: #Your Comment
Basic Syntax of a for loop
for item in iterable:
#code Block
The loop variable (item) takes each value from the iterable one by one.
1. Iterating over common types
#List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
#String (caracter by character)
for char in "Python":
print(char)
Output:
P
y
t
h
o
n
#Tuple
for num in (10, 20, 30):
print(num)
Output:
10
20
30
#Set (order is not guaranteed) it is random
for item in {"a", "b", "c"}:
print(item)
Output:
b
a
c
2. Using range
range() is the most common way to loop a specific number of times.
#0 to 4
for i in range(5):
print(i)
Output:
0
1
2
3
4
#2 to 7
for i in range(2, 8):
print(i)
Output:
2
3
4
5
6
7
#0 to 10 with step 2
for i in range(0, 11, 2):
print(i)
Output:
0
2
4
6
8
10
#countdown
import time #importing time Library
for i in range(10, 0, -1):
time.sleep(1) #waits one secont here in that case before printing in console
print(i)
print("Waiting")
Output:
10
Waiting
9
Waiting
8
Waiting
7
Waiting
6
Waiting
5
Waiting
4
Waiting
3
Waiting
2
Waiting
1
Waiting
3. Getting index + value -> enumerate()
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
#Start counting from 1
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output:
1 apple
2 banana
3 cherry
To be contiued soon ......