for Loop in Python
A for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range).
? Basic Syntax:
for item in sequence: # code block
? Examples
???? 1. Loop through a list
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)
???? 2. Using range()
# Print numbers from 0 to 4 for i in range(5): print(i)
???? 3. Using range(start, stop, step)
# Print even numbers from 2 to 10 for i in range(2, 11, 2): print(i)
???? 4. Loop through a string
for char in "Python": print(char)
???? 5. Nested for loop
for i in range(1, 3): for j in range(1, 4): print(i, j)
???? Tip:
You can use break, continue, or else with for loops.
???? Example with break:
for i in range(5): if i == 3: break print(i)
???? Example with continue:
for i in range(5): if i == 2: continue print(i)
???? Example with else:
for i in range(3): print(i) else: print("Loop completed")