Python3 循环语句
while 与 for 循环、for...else、range()、break/continue 与 pass。
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.
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)sum 1..5 = 15
count = 3for 语句
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.
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)Python
Go
Rust
0 Python
1 Go
2 Rust
P
yfor...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.
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')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 * 3range() 函数
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.
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)))[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.
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")odd: 3
odd: 5
odd: 7
donepass 语句
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.
for letter in 'Python':
if letter == 'h':
pass
print('This is pass block')
print('Current letter:', letter)
def todo():
pass
print(todo())Current letter: P
Current letter: y
Current letter: t
This is pass block
Current letter: h
Current letter: o
Current letter: n
Nonewhile 循环
while 在条件为真时反复执行循环体,条件在每轮开始时检查。循环体里必须有让条件趋向为假的语句,否则就是死循环。
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)sum 1..5 = 15
count = 3for 语句
for 遍历任何可迭代对象:列表、字符串、字典、文件、生成器。它不需要下标变量,直接拿到元素本身;需要下标时配合 enumerate()。
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)Python
Go
Rust
0 Python
1 Go
2 Rust
P
yfor...else
for 可以带 else 子句:循环正常走完(没有被 break 中断)时执行 else。这是 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')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 * 3range() 函数
range(stop)、range(start, stop)、range(start, stop, step) 生成左闭右开的整数序列,是惰性对象,转成 list 才看到全部元素。步长为负时可倒序。
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)))[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 立刻跳出整个循环,continue 跳过本轮剩余语句直接进入下一轮。二者都会影响 else:只要执行过 break,else 就不执行。
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")odd: 3
odd: 5
odd: 7
donepass 语句
pass 是空语句,什么也不做,只用来占位以保持语法完整 —— 比如先写好分支骨架、稍后再填实现。它和注释不同,是真正的语句。
for letter in 'Python':
if letter == 'h':
pass
print('This is pass block')
print('Current letter:', letter)
def todo():
pass
print(todo())Current letter: P
Current letter: y
Current letter: t
This is pass block
Current letter: h
Current letter: o
Current letter: n
None