Loops in Python
Master for loops, while loops, loop control statements, and advanced iteration patterns in Python.
Loops in Python
Loops allow you to execute a block of code repeatedly. Python provides two main types: for and while loops.
For Loops
The for loop iterates over a sequence (list, tuple, string, range, etc.):
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range()
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Iterating with index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
While Loops
The while loop continues as long as the condition is true:
count = 0
while count < 5:
print(count)
count += 1
Loop Control Statements
break
Exits the loop immediately:
for i in range(10):
if i == 5:
break
print(i) # Prints 0-4
continue
Skips the rest of the current iteration:
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints odd numbers
else Clause
The else block runs when the loop completes without break:
for item in items:
if item == target:
print("Found!")
break
else:
print("Not found")
List Comprehensions
A concise way to create lists using loops:
# Traditional approach
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
Advanced Patterns
Nested Loops
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for cell in row:
print(cell, end=" ")
print()
zip() for Parallel Iteration
names = ["Alice", "Bob"]
ages = [30, 25]
for name, age in zip(names, ages):
print(f"{name} is {age}") Related Articles
Variables and Data Types
Learn about Python variables, data types, type casting, and dynamic typing. A comprehensive guide for beginners.
Classes and Objects
Understanding object-oriented programming in Python with classes, objects, inheritance, and encapsulation.
Introduction to C++
Getting started with C++ programming — compiler setup, basic syntax, variables, and your first program.