To calculate 1+2+3, we can directly write the expression:
>>> 1 + 2 + 3
6
To calculate 1+2+3+…+10, we could just about write it out too.
However, to calculate 1+2+3+…+10000, writing the expression directly is impossible.
To enable computers to perform thousands upon thousands of repetitive calculations, we need loop statements.
Python has two types of loops:
for...in loop iterates over each element in a list or tuple in sequence. Here’s an example:names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
Executing this code will print each element in names sequentially:
Michael
Bob
Tracy
So, a for x in ... loop assigns each element to the variable x in turn and then executes the indented block of code.
Another example: if we want to calculate the sum of integers from 1 to 10, we can use a sum variable for accumulation:
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
Calculating the sum from 1 to 100 by writing out all numbers is cumbersome. Fortunately, Python provides the range() function, which generates a sequence of integers. This sequence can then be converted to a list using the list() function. For example, range(5) generates integers starting from 0 and less than 5:
>>> list(range(5))
[0, 1, 2, 3, 4]
range(101) will generate the sequence of integers from 0 to 100. The calculation becomes:
sum = 0
for x in range(101):
sum = sum + x
print(sum)
Please run the above code yourself and check if the result is 5050, the sum famously calculated mentally by the young Gauss.
while loop continues looping as long as a condition is met and exits when the condition becomes false. For example, to calculate the sum of all odd numbers within 100, we can use a while loop:sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
Inside the loop, the variable n is continuously decremented by 2. The loop exits when n becomes -1, as the condition n > 0 is no longer satisfied.
breakWithin a loop, the break statement allows you to exit the loop prematurely. For instance, consider a loop intended to print numbers from 1 to 100:
n = 1
while n <= 100:
print(n)
n = n + 1
print('END')
The code above prints numbers from 1 to 100.
To end the loop early, use the break statement:
n = 1
while n <= 100:
if n > 10: # When n = 11, the condition is met
break # The break statement terminates the current loop
print(n)
n = n + 1
print('END')
Executing this code will print numbers from 1 to 10, followed immediately by END, and then the program finishes.
Thus, the role of break is to terminate the loop early.
continueDuring loop execution, the continue statement skips the rest of the current iteration and immediately starts the next one.
n = 0
while n < 10:
n = n + 1
print(n)
The program above prints numbers from 1 to 10. However, if we want to print only the odd numbers, we can use the continue statement to skip certain iterations:
n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # If n is even
continue # Skip the rest of this iteration and start the next
print(n)
Executing this code will print not 1 to 10, but rather: 1, 3, 5, 7, 9.
Thus, the role of continue is to end the current iteration prematurely and start the next one immediately.
Loops are an effective way to make computers perform repetitive tasks.
The break statement terminates the loop immediately during execution, while the continue statement ends the current iteration prematurely and starts the next one. Both statements must usually be used in conjunction with an if statement.
Special Note: Avoid overusing break and continue. They can lead to code with excessive branching, making it more error-prone and harder to read. Most loops do not require these statements. The examples above could be rewritten by adjusting the loop condition or logic to eliminate the need for break and continue.
Sometimes, due to programming errors, a program can get stuck in an “infinite loop”, meaning it loops forever. In such cases, you can interrupt the program with Ctrl+C or forcefully terminate the Python process.
Please try writing an infinite loop program.