Loops are a fundamental programming concept that allow for a set of instructions to be executed repeatedly based on a condition or a sequence. Python supports two primary types of loops: while
and for
.
while
LoopThe while
loop repeatedly executes its block of code as long as its condition remains True
.
Syntax:
while condition:
# code to execute while condition is True
Example:
count = 0
while count < 5:
print(count)
count += 1
for
LoopThe for
loop is used to iterate over sequences (like lists, tuples, strings) or other iterable objects.
Syntax:
for variable in sequence:
# code to execute for each item in sequence
Example with a List:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
range()
FunctionThe range()
function generates a sequence of numbers and is often used with the for
loop to iterate a certain number of times.
Syntax and Variations:
range(stop) # from 0 to stop-1
range(start, stop) # from start to stop-1
range(start, stop, step) # from start to stop-1 with step increments
Example:
for i in range(5):
print(i)
Loops can be nested within each other to handle more complex scenarios.
Example:
for i in range(3):
for j in range(2):
print(f"(i, j) = ({i}, {j})")
break
and continue
Statementsbreak
: Exits the current loop entirely.continue
: Skips the remaining code in the current iteration and moves to the next iteration.Example:
for i in range(5):
if i == 3:
break
print(i)
# Outputs: 0, 1, 2
for i in range(5):
if i == 3:
continue
print(i)
# Outputs: 0, 1, 2, 4
else
Clause in LoopsAn often-overlooked feature is the else
clause in loops. It executes after the loop completes normally (i.e., without encountering a break
).
Example:
for i in range(5):
print(i)
else:
print("Loop completed!")
List comprehensions provide a concise way to create lists using a loop.
Syntax:
[expression for item in iterable if condition]
Example:
squared_numbers = [x**2 for x in range(5) if x % 2 == 0]
print(squared_numbers) # Outputs: [0, 4, 16]
Loops empower developers to perform repetitive tasks efficiently and are foundational in algorithm development. Grasping the intricacies of while
and for
loops, coupled with mastery over associated control statements like break
and continue
, ensures that a programmer can craft solutions for a wide array of challenges. As always, the key lies in practice and application, ensuring that these concepts are internalized and readily recalled when needed.