What is a For Loop?
The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range).
Basic Syntax
for item in sequence:
# Code block to execute
Example: Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using the Range Function
The range() function generates a sequence of numbers.
for num in range(5):
print(num) # Prints 0 to 4
Looping Through a String
for char in "Python":
print(char)
Iterating Over a Dictionary
student = {"name": "Alice", "age": 25, "grade": "A"}
for key, value in student.items():
print(key, ":", value)
Using Else with For Loop
An optional else block runs when the loop completes normally.
for num in range(3):
print(num)
else:
print("Loop completed")
Nested For Loops
A loop inside another loop.
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
Break Statement
The break statement exits the loop when a condition is met.
for num in range(10):
if num == 5:
break
print(num)
Continue Statement
The continue statement skips the current iteration and moves to the next.
for num in range(5):
if num == 2:
continue
print(num)