I. What Is a Loop Statement?
A loop is a control flow structure that allows a program to repeatedly execute a block of code when certain conditions are met.
Without loops, if you need to process one hundred pieces of data, you might need to write similar code one hundred times. A loop can abstract the repeated logic into a single structure, allowing the program to perform multiple executions automatically.
For example, to print five numbers:
print(1)
print(2)
print(3)
print(4)
print(5)
Using a loop, it can be simplified to:
for number in range(1, 6):
print(number)
Both approaches produce the same output, but the loop is more concise and easier to adapt to changes in data scale.
1. Basic Components of a Loop
A complete loop usually consists of the following parts:
| Component | Purpose |
|---|---|
| Loop condition or iterable object | Determines whether to continue executing and where to obtain data |
| Loop variable | Stores the data or state of the current iteration |
| Loop body | Code to be executed on each iteration |
| State update | Changes the loop variable or related state |
| Termination condition | Determines when the loop ends |
The core difference between for and while lies in how they control the loop:
for: Retrieves elements from an iterable one by one until the elements are exhausted.while: Executes the loop body continuously as long as the condition is true.
2. Basic Process of Loop Execution
flowchart TD
A["Start loop"] --> B["Check iterable or loop condition"]
B --> C{"Can continue?"}
C -->|Yes| D["Execute loop body"]
D --> E["Update loop state or get next element"]
E --> B
C -->|No| F["Exit loop"]
F --> G["Execute code after the loop"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
II. The for Loop
A for loop is used to iterate over an iterable, retrieving its elements one by one and executing the loop body.
It is particularly suitable for processing lists, tuples, strings, dictionaries, sets, files, and other iterable objects.
1. Basic Syntax
for variable in iterable:
loop_body
Execution process:
- Obtain an iterator for the iterable.
- Retrieve the next element from the iterator.
- Bind the element to the loop variable.
- Execute the loop body.
- Continue retrieving the next element.
- When the iterator is exhausted, the loop ends.
Example:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
Output:
Alice
Bob
Charlie
On each iteration, the variable name is bound to the currently retrieved element.
2. Iterating Over a List
Lists are one of the most common iterable objects.
numbers = [10, 20, 30, 40, 50]
for number in numbers:
print(number)
You can perform calculations during iteration:
prices = [19.9, 29.9, 39.9]
total = 0
for price in prices:
total += price
print(total)
Output:
89.7
Here, the loop retrieves each product price one by one and accumulates it into total.
3. Iterating Over a String
Strings are also iterable objects; when iterated over, their characters are retrieved one by one.
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n
This approach is commonly used for character counting, text processing, and string analysis.
For example, to count the letters in a string:
text = "hello python"
count = 0
for char in text:
if char.isalpha():
count += 1
print(count)
Output:
11
4. Iterating Over Tuples
Tuples also support for iteration:
coordinates = (10, 20, 30)
for coordinate in coordinates:
print(coordinate)
Tuples are iterated in basically the same way as lists; the main difference is that tuples themselves are immutable.
5. Iterating Over Sets
Sets support iteration, but a set does not guarantee that elements are provided in insertion order.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
The output order should not be treated as a fixed order.
If you need stable ordering, you can first use sorted():
colors = {"red", "green", "blue"}
for color in sorted(colors):
print(color)
6. Iterating Over Dictionaries
There are three common ways to iterate over a dictionary.
Iterating over keys:
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
for key in user:
print(key)
By default, iterating over a dictionary gives you the keys.
You can also explicitly use keys():
for key in user.keys():
print(key)
Iterating over values:
for value in user.values():
print(value)
Iterating over keys and values at the same time:
for key, value in user.items():
print(key, value)
items() returns an iterable view made up of key-value pairs; in the loop, you can unpack it to get two variables directly.
7. Using range() to Control the Number of Loop Iterations
range() is a commonly used tool in Python for generating integer sequences, and it is often used together with for.
Basic forms:
range(stop)
range(start, stop)
range(start, stop, step)
Parameter meanings:
| Parameter | Meaning |
|---|---|
| start | Starting value; defaults to 0 |
| stop | End boundary; this value is not included |
| step | Step size; defaults to 1 |
Starting from 0:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Specifying start and end values:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Specifying a step size:
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
Iterating in reverse order:
for i in range(5, 0, -1):
print(i)
Output:
5
4
3
2
1
Note that the end value of range() is never included in the result.
In addition, range() returns a lazy range object; it does not directly create a complete list of integers.
numbers = range(1, 6)
print(type(numbers))
print(list(numbers))
Output:
<class 'range'>
[1, 2, 3, 4, 5]
For iterating over large ranges of integers, range() is usually more memory-efficient than building a complete list up front.
8. Use enumerate() to get the index and value
Sometimes when iterating over a list you need not only the element, but also the position of the current element.
You can use enumerate():
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 orange
The default index starts at 0, but you can also specify a starting index:
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output:
1 apple
2 banana
3 orange
Compared with maintaining an index manually, enumerate() is more concise and less prone to index-update errors.
9. Use zip() to iterate over multiple objects at once
zip() can pair up multiple iterables by position.
names = ["Alice", "Bob", "Charlie"]
scores = [90, 85, 95]
for name, score in zip(names, scores):
print(name, score)
Output:
Alice 90
Bob 85
Charlie 95
By default, zip() stops when the shortest iterable is exhausted.
names = ["Alice", "Bob", "Charlie"]
scores = [90, 85]
for name, score in zip(names, scores):
print(name, score)
Output:
Alice 90
Bob 85
If you want to detect mismatched lengths, you can use strict=True, available in Python 3.10 and later:
names = ["Alice", "Bob", "Charlie"]
scores = [90, 85]
for name, score in zip(names, scores, strict=True):
print(name, score)
Because the lengths differ, the program raises a ValueError.
10. The for loop and the iterable protocol
The key to understanding for is understanding Python's iteration protocol.
An object can become an iterable by implementing the iteration protocol.
Two main concepts are involved:
__iter__(): returns an iterator.__next__(): returns the next element; raisesStopIterationwhen there are no more elements.
Example:
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
10
20
30
Calling next() again:
print(next(iterator))
triggers StopIteration.
The for loop handles iterator exhaustion internally, so you usually don't need to catch StopIteration manually.
The following pseudocode can help you understand how for works:
iterator = iter(numbers)
while True:
try:
item = next(iterator)
except StopIteration:
break
print(item)
This is not a bytecode-by-bytecode implementation of the for loop, but a simplified model for understanding its iteration protocol.
11. Custom iterable objects
We can also create our own iterator by implementing __iter__() and __next__().
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for number in Countdown(3):
print(number)
Output:
3
2
1
Here, Countdown implements both iterable and iterator behavior.
Note that iterators are usually stateful and may be exhausted after one traversal. If you want to traverse repeatedly, the iterable object should usually return a new iterator each time through __iter__().
III. while Loops
A while loop is a condition-driven loop structure.
As long as the condition expression evaluates to true in a truth-value test, the loop body will continue to execute.
1. Basic Syntax
while 条件:
循环体
Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Execution process:
- Initialize the loop variable.
- Check the loop condition.
- If the condition is true, execute the loop body.
- Update the loop variable.
- Check the condition again.
- If the condition is false, exit the loop.
2. The Execution Flow of while
flowchart TD
A["Initialize loop state"] --> B["Check while condition"]
B --> C{"Is the condition true?"}
C -->|Yes| D["Execute loop body"]
D --> E["Update loop state"]
E --> B
C -->|No| F["Exit loop"]
F --> G["Continue executing subsequent code"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3. Counting with while
count = 0
while count < 5:
print(f"当前次数:{count}")
count += 1
Output:
当前次数:0
当前次数:1
当前次数:2
当前次数:3
当前次数:4
Here, count += 1 is a very important state update operation.
If the loop variable is not updated, the condition may always be true, resulting in an infinite loop.
4. Handling User Input with while
while is often used in programs that need to wait repeatedly for user input.
For example, requiring the user to enter the correct password:
correct_password = "python123"
while True:
password = input("请输入密码:")
if password == correct_password:
print("登录成功")
break
print("密码错误,请重新输入")
Here, while True is used to create a continuous loop, and break controls exiting it.
In real-world applications, you should also add mechanisms such as a limit on the number of failed attempts, input validation, and authentication; a hard-coded password should not be used as the security solution for a real system.
5. Using while for Tasks with an Unknown Number of Iterations
When you cannot determine in advance how many times to loop, while is particularly useful.
For example, continuously reading data until an end marker is received:
```python while True: data = input("Please enter content (type quit to exit): ") if data == "quit": print("Program ended") break print(f"Received content: {data}") ```In this type of scenario, the number of loop iterations depends on external input rather than a predetermined number.
6. A Common Pitfall of while: Infinite Loops
If the loop condition is always true and there is no effective exit mechanism, the loop may run forever.
Incorrect example:
count = 1
while count <= 5:
print(count)
Here count is always 1, so the condition is always true.
Correct way:
count = 1
while count <= 5:
print(count)
count += 1
When designing a while loop, focus on checking:
- Whether the initial state is correct.
- Whether the loop condition is reasonable.
- Whether the loop body changes the relevant state.
- Whether there is a reachable exit condition.
- Whether external input or exceptional situations may prevent the loop from ending.
7. while and Conditional Expressions
The condition of a while loop does not have to be a comparison expression; it can also be any object that can be evaluated for truthiness.
items = [1, 2, 3]
while items:
item = items.pop()
print(item)
Output:
3
2
1
When the list is empty, its truth value is False, and the loop ends naturally.
This style is suitable for handling queues, stacks, and lists of pending tasks.
IV. The Core Differences Between for and while
Both for and while can implement repeated execution, but they control it in different ways.
1. Comparison of Syntax and Use Cases
| Comparison Dimension | for | while |
|---|---|---|
| Control method | Iterate over an iterable object | Evaluate a condition |
| Suitable scenarios | Iterating over collections, sequences, files | Waiting for conditions, state changes |
| Number of iterations | Usually determined by the iterable object | Determined by changes in the condition |
| State updates | Usually managed by the iterator | Usually require manual management |
| Risk of infinite loops | Generally lower | Relatively higher |
| Typical uses | Batch data processing | Interaction, polling, waiting for tasks |
2. Two Implementations of the Same Task
For example, calculate the cumulative sum from 1 to 100.
Using for:
total = 0
for number in range(1, 101):
total += number
print(total)
Using while:
total = 0
number = 1
while number <= 100:
total += number
number += 1
print(total)
Both approaches produce:
5050
But for is more direct because the loop range is already determined; while, on the other hand, requires manual initialization and updating of the loop variable.
3. How to Choose
You can refer to the following principles:
When to prefer for:
- Iterating over a list, tuple, dictionary, or set.
- Iterating over the characters in a string.
- Reading each line in a file.
- Performing a repeated task over a fixed range.
- Iterating over a generator or other iterator.
When to prefer while:
- Waiting for a certain condition to become true.
- Determining the number of iterations based on user input.
- Handling a task that continues until a certain state is reached.
- Implementing a retry mechanism.
- Implementing polling, state monitoring, and continuously running logic.
The core principle is: if you already know what needs to be iterated over, prefer for; if you need to continue until a certain condition is met, prefer while.
V. Loop Control Statements: break, continue, and pass
Python provides three control statements that are often used with loops:
break: immediately terminate the current loop.continue: end the current iteration and move on to the next one.pass: do nothing; it serves as a syntactic placeholder.
1. break: Terminating a Loop
break immediately exits the nearest enclosing loop.
for number in range(1, 10):
if number == 5:
break
print(number)
Output:
1
2
3
4
When number == 5, break is executed, and the entire loop ends.
The same applies in while:
count = 0
while True:
count += 1
if count == 3:
break
print(count)
Output:
1
2
2. continue: Skip the current iteration
continue does not terminate the entire loop; it only skips the remaining code in the current loop body and proceeds directly to the next iteration.
for number in range(1, 6):
if number == 3:
continue
print(number)
Output:
1
2
4
5
When number == 3, the remaining code in this iteration is not executed, but the loop still continues.
When using continue in a while loop, pay special attention to where the state is updated.
Incorrect example:
count = 0
while count < 5:
if count == 2:
continue
print(count)
count += 1
When count equals 2, the program keeps executing continue, skips count += 1, and causes an infinite loop.
Correct version:
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
Output:
1
2
4
5
3. pass: Empty operation placeholder
pass does not change the loop state and does not skip the current iteration.
for number in range(5):
if number == 2:
pass
print(number)
Output:
0
1
2
3
4
It is usually used to temporarily preserve the code structure:
while True:
pass
Although this code is syntactically valid, it keeps consuming CPU to execute the loop, and it should not be used as an actual waiting mechanism.
4. Comparison of break, continue, and pass
| Statement | Current loop body | Subsequent iterations | Whether loop terminates |
|---|---|---|---|
| break | Ends immediately | Not executed again | Yes |
| continue | Skips remaining part | Continues executing | No |
| pass | Continues normally | Executes normally | No |
5. Loop control flowchart
flowchart TD
A["Enter loop"] --> B["Execute loop body"]
B --> C{"Encounter a control statement?"}
C -->|break| D["Exit the loop immediately"]
C -->|continue| E["Skip remaining code in this iteration"]
C -->|pass| F["Do nothing and continue"]
C -->|Normal statement| G["Execute subsequent code"]
E --> H["Proceed to next iteration"]
F --> G
G --> H
H --> A
D --> I["Execute code after the loop"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
6. The else Clause in Loops
Python's for and while both support an else clause.
Its meaning is different from if-else:
elseis executed when the loop ends normally.- When the loop is terminated by
break,elseis not executed. - If the loop body executes
continueand the loop eventually ends normally,elseis still executed.
1. for-else
for number in range(3):
print(number)
else:
print("循环正常结束")
Output:
0
1
2
循环正常结束
Since the iterable has been exhausted and no break occurred, else is executed.
2. break skips else
for number in range(5):
if number == 2:
break
print(number)
else:
print("循环正常结束")
Output:
0
1
The loop is terminated early by break, so else is not executed.
3. while-else
count = 0
while count < 3:
print(count)
count += 1
else:
print("循环正常结束")
Output:
0
1
2
循环正常结束
The while condition becomes false and the loop ends naturally, so else is executed.
4. Using loop else to implement search
One of the most typical uses of the loop else is to determine whether a target element has been found.
numbers = [10, 20, 30, 40, 50]
target = 30
for number in numbers:
if number == target:
print("找到了")
break
else:
print("没有找到")
Output:
找到了
If the target is not found:
numbers = [10, 20, 30, 40, 50]
target = 100
for number in numbers:
if number == target:
print("找到了")
break
else:
print("没有找到")
Output:
没有找到
This structure avoids the need to set an additional found flag variable.
5. Execution logic of loop else
flowchart TD
A["Enter a for or while loop"] --> B["Execute the loop"]
B --> C{"Is break encountered?"}
C -->|Yes| D["Exit the loop immediately"]
C -->|No| E{"Does the loop end normally?"}
E -->|Yes| F["Execute the else clause"]
E -->|No| B
D --> G["Skip else"]
F --> H["Continue with the following code"]
G --> H
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that when a loop is exited because of an exception, a function return, or another such way, the loop's else will also not be executed. The key point in judging a loop's else is whether it was terminated early via break, not simply whether the loop body was ever executed.
7. Nested Loops
A nested loop is a loop defined inside another loop.
It is commonly used for two-dimensional data, matrices, tables, combinatorial enumeration, and multi-level data structures.
1. Basic Structure
for 外层变量 in 外层可迭代对象:
for 内层变量 in 内层可迭代对象:
循环体
Each time the outer loop executes once, the inner loop usually executes completely once, unless it is interrupted early by a control statement or other control flow.
2. Two-Level Loop Example
for row in range(3):
for column in range(3):
print(row, column)
Output:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
The outer loop executes 3 times, and the inner loop executes 3 times each time, so the total number of executions is:
3. Print a Multiplication Table
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j} × {i} = {i * j}", end="\t")
print()
Here:
- The outer loop controls the number of rows.
- The inner loop controls the number of columns in each row.
end="\t"arranges the content of the same row horizontally.- After the inner loop ends,
print()moves to a new line.
4. Iterate Over a 2D List
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Output:
1 2 3
4 5 6
7 8 9
This approach is suitable for iterating over two-dimensional arrays, matrices, and tabular data.
5. break in Nested Loops
break only terminates the nearest loop it is currently in; it does not automatically terminate all outer loops.
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)
Output:
0 0
1 0
2 0
Whenever j in the inner loop equals 1, the inner loop exits, and then the outer loop continues to the next iteration.
If you want to end multiple levels of loops at the same time, you can use a flag variable, a function return, or another explicit control structure.
For example, using a flag variable:
found = False
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
found = True
break
if found:
break
print("搜索结束")
6. Performance Issues of Nested Loops
If the outer loop runs m times and the inner loop runs n times each time, then the total number of iterations is usually:
The time complexity can usually be expressed as:
If both loops have a scale of n, then it is usually:
Therefore, when processing large amounts of data, care should be taken to avoid unnecessary nested loops.
For example, to find common elements in two lists:
list_a = [1, 2, 3, 4, 5]
list_b = [3, 4, 5, 6, 7]
common = []
for a in list_a:
for b in list_b:
if a == b:
common.append(a)
print(common)
This implementation needs to compare combinations of elements in the two lists.
If duplicates do not need to be preserved, set operations can be considered:
list_a = [1, 2, 3, 4, 5]
list_b = [3, 4, 5, 6, 7]
common = set(list_a) & set(list_b)
print(common)
For large-scale data, an appropriate data structure is often more important than simply optimizing loop syntax.
8. Common Loop Application Patterns
Loops are not only used for simple counting but also form the foundation of many practical programs.
1. Accumulator Pattern
An accumulator is used to continuously collect computation results.
numbers = [10, 20, 30, 40]
total = 0
for number in numbers:
total += number
print(total)
Output:
100
Common uses:
- Summing values.
- Calculating a total amount.
- Accumulating points.
- Calculating total duration.
2. Counter Pattern
A counter is used to count the number of elements that meet a certain condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
count = 0
for number in numbers:
if number % 2 == 0:
count += 1
print(count)
Output:
4
Here, it counts the number of even numbers in the list.
3. Maximum and Minimum Pattern
You can maintain the current maximum or minimum value in a loop.
scores = [78, 92, 85, 96, 88]
maximum = scores[0]
for score in scores:
if score > maximum:
maximum = score
print(maximum)
Output:
96
In actual development, if you only need to get the maximum value, it is usually more recommended to use built-in functions directly:
maximum = max(scores)
minimum = min(scores)
Implementing the loop yourself helps you understand algorithms and is also suitable for scenarios that require additional conditions.
4. Filtering Pattern
Iterate through the data and keep only elements that meet the condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
print(even_numbers)
Output:
[2, 4, 6]
For simple filtering, you can also use a list comprehension:
even_numbers = [
number
for number in numbers
if number % 2 == 0
]
5. Search Pattern
Iterate through the data to find elements that satisfy the condition.