In Python, loops are used to execute a block of code repeatedly.
The two main types of
loops are for loops and while loops.
1. For Loop
The for loop iterates over each element in a sequence (like a list, tuple, string, or range) and
executes the block of code for each element.
Basic Syntax
for element in sequence:
# Code to execute
Example
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Using range() with for loop
The range() function generates a sequence of numbers and is commonly used with for
loops.
# Loop from 0 to 4
for i in range(5):
print(i)
# Output:
#0
#1
#2
#3
#4
2. While Loop
The while loop repeats a block of code as long as a specified condition is True.
Basic Syntax
while condition:
# Code to execute
Example
# Print numbers from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1
# Output:
#1
#2
#3
#4
#5
Loop Control Statements
Loop control statements can modify the normal behavior of loops.
1. break Statement
The break statement immediately terminates the loop and moves to the code following the
loop.
for i in range(10):
if i == 5:
break
print(i)
# Output:
#0
#1
#2
#3
#4
2. continue Statement
The continue statement skips the current iteration and moves to the next iteration.
for i in range(5):
if i == 2:
continue
print(i)
# Output:
#0
#1
#3
#4
3. else Clause with Loops
The else clause in a loop runs if the loop completes normally (without hitting a break
statement).
for i in range(5):
print(i)
else:
print("Loop finished")
# Output:
#0
#1
#2
#3
#4
# Loop finished
Example of Combining Loops and Control Statements
# Print if numbers from 1 to 5 are even or odd
for num in range(1, 6):
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
# Output:
# 1 is odd
# 2 is even
# 3 is odd
# 4 is even
# 5 is odd
Summary
for loop: Iterates over items in a sequence.
while loop: Repeats while a condition is True.
Control Statements: break, continue, and else can change loop behavior.