Appearance
Loops
To calculate 1 + 2 + 3
, we can directly write the expression:
python
>>> 1 + 2 + 3
6
However, calculating 1 + 2 + 3 + ... + 10000
would be nearly impossible using just expressions. To perform thousands of repetitive calculations, we need loop statements.
Python supports two types of loops: for...in
loops and while
loops.
for...in
Loops
The for...in
loop iterates over each element in a list or tuple. For example:
python
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
Executing this code will print each element in the list names
:
Michael
Bob
Tracy
In the for x in ...
loop, each element is assigned to the variable x
, and the indented block is executed.
To calculate the sum of integers from 1 to 10, we can use a variable sum
for accumulation:
python
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
If we want to calculate the sum from 1 to 100, manually writing the list would be difficult. Fortunately, Python provides the range()
function, which generates a sequence of integers. For example, range(5)
generates a sequence of integers from 0 to less than 5:
python
>>> list(range(5))
[0, 1, 2, 3, 4]
Using range(101)
, we can generate the sequence 0 to 100:
python
sum = 0
for x in range(101):
sum = sum + x
print(sum)
Running the above code will give the result 5050, just as Gauss famously calculated.
while
Loops
A while
loop continues executing as long as the condition is true. When the condition becomes false, the loop exits. For example, to calculate the sum of all odd numbers below 100:
python
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
In this example, the variable n
is decreased by 2 in each iteration until it reaches -1, at which point the while
condition is no longer satisfied, and the loop exits.
Exercise
Print "Hello, xxx!" for each name in the list:
python
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print(f'Hello, {name}!')
break
The break
statement allows us to exit a loop prematurely. For example, the following code prints numbers from 1 to 100:
python
n = 1
while n <= 100:
print(n)
n = n + 1
print('END')
To stop the loop early, we can use the break
statement:
python
n = 1
while n <= 100:
if n > 10: # When n = 11, break the loop
break
print(n)
n = n + 1
print('END')
The output will be numbers from 1 to 10, followed by "END." The break
statement exits the loop when the condition is met.
continue
The continue
statement skips the current iteration and proceeds to the next iteration:
python
n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # Skip even numbers
continue
print(n)
The output will be 1, 3, 5, 7, 9
, skipping even numbers.
Summary
Loops are an effective way to make the computer perform repetitive tasks.
- The
break
statement exits the loop, while thecontinue
statement skips to the next iteration. Both are often used withif
statements. - Avoid overusing
break
andcontinue
as they can make the code more complex. In most cases, loops can be written without them. - Be cautious of infinite loops (deadlocks). Use
Ctrl+C
to exit or forcibly terminate the Python process.
Exercise: Write an infinite loop program.