Python循环用来把同一段代码重复执行多遍。Python 语言提供两种:for 按序列逐项遍历,while 在条件为真时一直跑。两者都可以带 else,在循环正常结束(没被 break 打断)时执行。
要把列表里每个数加总,或者反复读输入直到用户敲 0,就得靠它们。
for:遍历序列
for 会依次取出可迭代对象(列表、字符串、元组、字典等)里的每一项:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
total = 0
for val in numbers:
total = total + val
print("总和是", total) # 总和是 48range():生成数字序列
若只是想固定循环 N 次,不必手写列表,用 range 即可:
print(list(range(10))) # [0,1,2,3,4,5,6,7,8,9]
print(list(range(2, 8))) # [2,3,4,5,6,7]
print(list(range(2, 20, 3))) # [2,5,8,11,14,17]
for i in range(5):
print(i, end=" ") # 0 1 2 3 4rangestart, stop, step) 里,start 默认 0,step 默认 1,stop 本身不包含在结果中。
用索引遍历 + len()
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like", genre[i])输出:
I like pop
I like rock
I like jazzfor ... else
循环完整跑完、中途没有 break 时,会执行 else 块:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("没有剩余的项目")输出:
0
1
5
没有剩余的项目查找场景里很有用:循环中找到目标就 break,else 被跳过,全部找完仍没命中,才进入 else 做未找到处理:
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
student_name = 'Soyuj'
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('没有找到该名称的条目')while:条件成立就一直循环
不知道要转多少圈时,用 while 更合适,条件为真就进入循环体,跑完再回来重新判断:
n = 10
total = 0
i = 1
while i <= n:
total = total + i
i = i + 1
print("1+2+...+10 =", total) # 55计数器要记得更新(例如 i = i + 1),漏掉的话条件会一直为真,程序就停不下来。
while 循环流程:先判断条件,为真进入循环体,跑完回到条件再判断
while ... else
条件变成 False、循环自然结束时会执行 else,中途若被 break 打断,else 不会跑:
counter = 0
while counter < 3:
print("内部循环")
counter = counter + 1
else:
print("else 语句")输出:
内部循环
内部循环
内部循环
else 语句for 还是 while?
| 场景 | 用哪个 |
|---|---|
| 遍历列表 / 字符串 / 固定次数 | for |
| 直到某条件满足才停(次数未知) | while |
| 无限循环直到输入退出 | while True + break |
试着写两个小程序
用 for 算出 1 到 100 的和。另写一个 while 累计器:不断读入数字,读到 0 就停,最后打印累计和。