Python学习笔记-循环for&while

xiaoxiao2021-02-27  403

for

# 打印list: names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) # 打印数字 0 - 9 for x in range(10): print(x) #计算1+2+3...+100 sum = 0 for x in range(101): sum = sum + x print(sum)

while

# 计算1+2+3+...+100: sum = 0 n = 1 while n <= 100: sum = sum + n n = n + 1 print(sum) # 计算1x2x3x...x100: acc = 1 n = 1 while n <= 100: acc = acc * n n = n + 1 print(acc)

结束当前循环break

sum = 0 for x in range(101): sum = sum + x print(sum)

也可以通过continue语句,跳过当前的这次循环,直接开始下一次循环。

n = 0 while n < 10: n = n + 1 if n % 2 == 0: # 如果n是偶数,执行continue语句 continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行 print(n)
转载请注明原文地址: https://www.6miu.com/read-4184.html

最新回复(0)