3.2 Loops: for and while
Loops are fundamental control flow structures in programming that allow you to repeat a block of code multiple times. In Python, there are two main types of loops: the for
loop and the while
loop. Both loops serve different purposes but can be used to iterate over data structures, such as lists, strings, or ranges, and perform repeated actions until a condition is met.
3.2.1 The for
Loop
A for
loop is used to iterate over a sequence of items (like a list, string, tuple, or range) and execute a block of code for each item. It’s particularly useful when you know the number of iterations beforehand.
Syntax:
for variable in sequence:
# Code to execute for each item in the sequence
variable
: A placeholder that takes the value of each item in the sequence.sequence
: Any iterable data structure (like a list, tuple, string, or range).
3.2.1.1 Iterating Over a List
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the loop iterates over each item in the fruits
list, and fruit
takes the value of each item in turn.
3.2.1.2 Iterating Over a String
You can iterate over the characters of a string using a for
loop.
Example:
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
3.2.1.3 Iterating Using range()
The range()
function generates a sequence of numbers. It is commonly used with for
loops when you want to repeat a block of code a certain number of times.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
In this case, range(5)
generates the numbers from 0
to 4
(excluding 5
), and the loop iterates over them.
3.2.1.4 Iterating with range(start, stop, step)
The range()
function can also take three arguments: start
, stop
, and step
. This allows you to specify a custom starting point, stopping point, and step size.
Example:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
In this example, range(1, 10, 2)
generates numbers from 1
to 9
, stepping by 2
.
3.2.2 The while
Loop
A while
loop repeats a block of code as long as a specified condition remains True
. It is particularly useful when you don’t know in advance how many times you need to iterate and instead rely on a condition to determine when to stop.
Syntax:
while condition:
# Code to execute as long as the condition is True
condition
: A Boolean expression. The loop continues to execute as long as this condition evaluates toTrue
.
3.2.2.1 Basic while
Loop
Example:
x = 0
while x < 5:
print(x)
x += 1
Output:
0
1
2
3
4
In this example, the loop continues to execute as long as x < 5
. After each iteration, x
is incremented by 1
, and when x
becomes 5
, the loop terminates.
3.2.2.2 Infinite Loops
A while
loop will continue indefinitely if the condition never becomes False
. This is called an infinite loop. To avoid infinite loops, ensure that the condition is modified inside the loop.
Example of an infinite loop:
while True:
print("This is an infinite loop!")
In this case, since the condition is always True
, the loop will never stop. You can break out of an infinite loop using the break
statement (explained later).
3.2.3 Control Flow in Loops: break
and continue
Python provides two important control flow statements—break
and continue
—which allow you to alter the behavior of loops.
3.2.3.1 The break
Statement
The break
statement is used to exit the loop prematurely, even if the loop’s condition is still True
. This is useful when you want to stop the loop based on a specific condition that occurs during execution.
Example:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
In this example, the loop stops when i
becomes 5
, and the break
statement is executed.
3.2.3.2 The continue
Statement
The continue
statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration. It does not terminate the loop like break
.
Example:
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
Here, when i
is 3
, the continue
statement is executed, causing the loop to skip printing 3
and move to the next iteration.
3.2.4 Nested Loops
You can place one loop inside another loop. These are called nested loops. Nested loops are useful for iterating over multi-dimensional data structures like lists of lists.
Example of a Nested Loop:
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
Output:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
In this example, the outer loop iterates over i
, and for each value of i
, the inner loop iterates over j
.
3.2.5 else
Clause with Loops
Both for
and while
loops can have an else
clause in Python. The else
block is executed when the loop finishes normally (i.e., without encountering a break
statement).
Example with for
Loop:
for i in range(5):
print(i)
else:
print("Loop finished without break.")
Output:
0
1
2
3
4
Loop finished without break.
Example with while
Loop:
x = 0
while x < 3:
print(x)
x += 1
else:
print("Loop finished without break.")
Output:
0
1
2
Loop finished without break.
If the loop is terminated by a break
statement, the else
block is not executed.
Example with break
:
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't be printed because of the break.")
Output:
0
1
2
In this case, since the loop is broken at i == 3
, the else
block is not executed.
3.2.6 Summary
- The
for
loop is used to iterate over sequences like lists, strings, or ranges. - The
while
loop continues to execute as long as its condition isTrue
. It’s useful when the number of iterations isn’t known ahead of time. - The
break
statement allows you to exit a loop prematurely, while thecontinue
statement skips the rest of the current iteration and moves to the next. - Nested loops can be used to handle multi-dimensional data.
- You can use an
else
clause with loops to execute code after the loop finishes, unless the loop is terminated by abreak
.
Understanding loops is essential for writing efficient and repetitive code in Python, and they are commonly used in everything from simple iterations to complex algorithms.