与其他编程语言一样,python的循环语句也用for 和while
12.1 使用while计算1到100的和#!/usr/bin/env python3 n = 100 sum = 0 i = 1 while i <= n: sum = sum + i i = i + 1 print("1 到 %d 之和为: %d" % (n, sum))
结果:
1 到 100 之和为: 5050
12.2 使用for循环计算1到100的和#!usr/bin/python3 sum = 0 for i in range(1,101): sum = sum + i print("sum = ", sum)
结果:
sum = 5050
12.3 break 语句与其他编程语言一样,break用于跳出循环,请看下面的例子:
#!usr/bin/python3 for i in range(1,10): if i == 5: break print("i = ", i) #5以后的不会打印
结果:
i = 1
i = 2
i = 3
i = 4
与其他编程语言一样,continue语句用于跳出本次循环,执行下一次循环
#!usr/bin/python3 for i in range(1,10): if i == 5: continue print("i = ", i) #不会把5打印出来
结果:
i = 1
i = 2
i = 3
i = 4
i = 6
i = 7
i = 8
i = 9
一般在函数中,或循环中使用,表示跳过函数或循环
#!usr/bin/python3 for i in range(1,10): pass
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)