title: cycle description: A loop is a structure in programming used to repeatedly execute a block of code. Python provides two main loop constructs:

A must-learn for getting started with Python: full analysis of for/while loops and control statements

Whether it is batch processing of 100 local files, statistical database of 1,000 user records, or traversing 10,000 target links crawled by a crawler, Loop is the most basic and powerful "automated repetitive execution tool" in programming, which can help you completely free yourself from boring manual operations.

Python has officially prepared two sets of core loop solutions for developers, each with its own applicable scenarios. Let’s break it down one by one below.


1. Core classification of loops

Loops in Python are divided into two categories based on triggering logic:

  • forTraversal loop: explicitly executed according to "number of elements/number of iterations" - suitable for scenarios where it is known "how many objects" and "how many operations" to be processed
  • whileConditional loop: Continue execution according to "Boolean conditions" - suitable for scenarios where the specific end time is not sure, but it is clear "when it must stop"

2. forTraverse the loop

forThe core logic of the loop is to "remove the elements of the iterable object one by one until it is exhausted."

2.1 Basic syntax structure

Note that Python uses colon + indent to divide code blocks (indentation is usually 4 spaces, or 1 Tab automatically converted by the editor):

# 变量名建议取有语义的(比如遍历名字就用name,不要用i/x)
for 目标变量 in 可迭代对象:
    # 缩进后的代码才是循环体,每次取到新变量都会执行
    循环体代码

2.2 Common scenarios: traversing a sequence

Lists, tuples, strings, and dictionaries are all Python’s built-in iterable sequences. Let’s look at the most commonly used list traversal first:

# 遍历公司实习生名单
interns = ["Alice", "Bob", "Charlie"]
for intern in interns:
    print(f"请 {intern} 同学来会议室签到")

Run results:

请 Alice 同学来会议室签到
请 Bob 同学来会议室签到
请 Charlie 同学来会议室签到

2.3 Must-learn tools:range()Generate a sequence of integers

If you do not need to traverse specific objects and only need to perform "N fixed operations", you can userange()Function to quickly generate a sequence of integers as an iterator.

range()Three ways to pass parameters

Number of passed parametersFormatGeneration rangeSample output
1range(end)Integer from 0 to end-1range(5) → [0,1,2,3,4]
2range(start, end)Integer from start to end-1range(2,5) → [2,3,4]
3range(start, end, step)start to end-1 and the step size is an integerrange(1,10,2) → [1,3,5,7,9]

Example: Calculate the cumulative sum of 1-100

sum_total = 0
# range(1,101) 是因为「结束值不包含」,100刚好被包含进去
for num in range(1, 101):
    sum_total += num
print(f"1-100的累加和是:{sum_total}")

Run results:

1-100的累加和是:5050

3. whileconditional loop

whileThe loop will first check whether the condition is True, and if so, execute the loop body, and then check again after execution - note that there must be code to modify the condition in the loop body, otherwise it will become an "infinite loop".

3.1 Basic syntax structure

# 条件变量要先定义好!
条件变量 = 初始值
while 条件判断:
    # 循环体
    处理逻辑
    # 必须有修改条件的语句,比如 n += 1 或 n -= 2
    条件变量更新

3.2 Common scenarios: conditional accumulation

For example, usewhileCalculate the sum of all odd numbers up to 100:

sum_odd = 0
n = 99  # 从最大的奇数开始,递减更直观
while n > 0:
    sum_odd += n
    n -= 2  # 每次减2,自动跳过偶数
print(f"100以内奇数的和是:{sum_odd}")

Run results:

100以内奇数的和是:2500

4. Loop control statement

Sometimes we don't need to execute the entire loop completely - Python providesbreakandcontinueTwo keywords to intervene in the loop process.

4.1 break: Completely terminate the loop

Once encounteredbreak, The entire loop will jump out directly, and subsequent iterations will not be executed.

Example: Stop when finding the first number greater than 50

nums = [12, 34, 56, 78, 90]
for num in nums:
    if num > 50:
        print(f"找到第一个大于50的数:{num},停止搜索")
        break
    print(f"当前数 {num} 不大于50")

Run results:

当前数 12 不大于50
当前数 34 不大于50
找到第一个大于50的数:56,停止搜索

4.2 continue: Skip the current iteration

meetcontinue, The remaining code of the current iteration will be skipped and go directly to the next round of inspection.

Example: Only print odd numbers from 1-10

for n in range(1, 11):
    if n % 2 == 0:
        continue  # 是偶数就跳过print,直接下一轮
    print(n)

Run results:

1
3
5
7
9

5. Best practices and pitfalls of looping

Avoid Pitfall 1: WritewhileBe sure to add "conditional modification logic"

For example, the following code,nIt is always 1, the loop will print infinitely, and the program can only be forced to terminate:

# ❌ 错误示范:死循环
n = 1
while n < 10:
    print(n)
    # 缺少了 n += 1

Avoid Pitfall 2: Don’t Overusebreak/continue

Although they can simplify some codes, using them too much will make the execution logic of the loop "jump around" and make the readability worse - try to put the logic inwhileconditions orforin the iterator.

Best Practice 1: Use when traversing a sequence and requiring an indexenumerate()

Traditional methods (such as maintaining a separateindexvariables) are error-prone, Python has built-inenumerate()Functions can return both "index" and "element":

fruits = ["apple", "banana", "orange"]
for idx, fruit in enumerate(fruits):
    print(f"第 {idx+1} 个水果是:{fruit}")  # idx从0开始,通常要加1

Best Practice 2: Traverse multiple sequences in parallel withzip()

If you need to traverse two sequences of the same length (such as name and corresponding age) at the same time, you can usezip()Pack them into tuple iterations:

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} 今年 {age} 岁")

6. Entry-level exercises (with reference answers)

Exercise 1: Print greetings in batches

Print a personalized greeting for each person on your list:

# ✅ 参考答案
names = ["Bart", "Lisa", "Adam"]
for name in names:
    print(f"Hello, {name}!")

Exercise 2: Calculate the sum of even numbers from 1 to 100

using two methods (for+rangestep length,for+continue) you can try:

# ✅ 参考答案(更简洁的range步长法)
sum_even = 0
for num in range(2, 101, 2):
    sum_even += num
print(f"1-100的偶数和是:{sum_even}")

Exercise 3: Print the multiplication table (nested loop)

# ✅ 参考答案
for i in range(1, 10):  # i控制行数(1-9)
    for j in range(1, i+1):  # j控制每行的列数(1到i)
        # end="\t" 让每个式子之间用制表符对齐
        print(f"{j}×{i}={i*j}", end="\t")
    print()  # 每行结束后换行

7. Summary

Loops are the core tool for handling repetitive tasks in Python. Reasonable selection can greatly improve efficiency:

  1. Priority is givenforLoop: Traverse a sequence of known length/perform a fixed number of operations
  2. usewhileLoop: conditional execution (such as guessing a number game until you guess it right)
  3. Use control statements reasonably:breaktermination,continueSkip it, but don’t abuse it
  4. Make good use of built-in tools:range()enumerate()zip()Can simplify code

If you need more complex iteration functions (such as infinite iteration, combined iteration), you can follow up with the Python standard libraryitertoolsModule~