Loops are essential for repeating code without writing the same lines over and over. Python offers two main types of loops: for loops and while loops.
For Loops
For loops iterate over a sequence (like a list or range):
# Loop through a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop through a range of numbers
for i in range(5):
print(f"Count: {i}") # Prints 0 to 4
Range Function
The range() function generates sequences of numbers:
range(5) # 0, 1, 2, 3, 4
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8 (step by 2)
While Loops
While loops continue as long as a condition is true:
count = 0
while count < 5:
print(f"Count is {count}")
count += 1 # Important: update the condition!
Loop Control
Use break and continue to control loop behavior:
# Break: exit the loop early
for i in range(10):
if i == 5:
break
print(i) # Prints 0 to 4
# Continue: skip to next iteration
for i in range(5):
if i == 2:
continue
print(i) # Prints 0, 1, 3, 4
Practical Example
# Calculate sum of numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # Sum: 15
Loops save time and make your code more efficient by automating repetitive tasks.