Python3 循环语句

while 与 for 循环、for...else、range()、break/continue 与 pass。

Beginner
Key Pointswhile 用于未知次数、for 用于遍历可迭代对象;range() 生成整数序列,for...else 的 else 只在循环未被 break 时执行。

while 循环

while repeats while the condition holds; the condition is checked at the top of each pass. The body must move the condition toward false, otherwise it loops forever.

Python
n = 5
total = 0

while n > 0:
    total += n
    n -= 1

print("sum 1..5 =", total)

count = 0
while True:
    count += 1
    if count >= 3:
        break
print("count =", count)
Output
sum 1..5 = 15
count = 3

for 语句

for iterates over any iterable — lists, strings, dicts, files, generators. It yields items directly, so pair it with enumerate() when you also need the index.

Python
langs = ['Python', 'Go', 'Rust']

for x in langs:
    print(x)

for i, x in enumerate(langs):
    print(i, x)

for ch in 'Py':
    print(ch)
Output
Python
Go
Rust
0 Python
1 Go
2 Rust
P
y

for...else

A for loop may carry an else clause: it runs when the loop completes without hitting break. This Python-specific idiom is handy for "search failed" cases.

Python
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, '=', x, '*', n // x)
            break
    else:
        print(n, 'is a prime number')
Output
2 is a prime number
3 is a prime number
4 = 2 * 2
5 is a prime number
6 = 2 * 3
7 is a prime number
8 = 2 * 4
9 = 3 * 3

range() 函数

range(stop), range(start, stop), range(start, stop, step) produce a lazy, half-open integer sequence. Wrap it in list() to see everything; a negative step counts down.

Python
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 10, 3)))
print(list(range(-10, -100, -30)))
print(list(range(5, 0, -1)))
Output
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[0, 3, 6, 9]
[-10, -40, -70]
[5, 4, 3, 2, 1]

break 和 continue 语句及循环中的 else 子句

break leaves the whole loop; continue skips the rest of the current pass. Both affect else: once break runs, else is skipped.

Python
for n in range(2, 10):
    if n % 2 == 0:
        continue
    if n > 7:
        break
    print("odd:", n)
else:
    print("loop finished without break")

print("done")
Output
odd: 3
odd: 5
odd: 7
done

pass 语句

pass is the no-op statement. It exists to keep syntax valid while you sketch a branch and fill it in later. Unlike a comment, it is a real statement.

Python
for letter in 'Python':
    if letter == 'h':
        pass
        print('This is pass block')
    print('Current letter:', letter)

def todo():
    pass

print(todo())
Output
Current letter: P
Current letter: y
Current letter: t
This is pass block
Current letter: h
Current letter: o
Current letter: n
None

Friends & Partners