while 条件:
条件满足时,做的事情1
条件满足时,做的事情2
条件满足时,做的事情3
...(省略)...
while循环实例代码如下:
#第3章/xunhuan.py
i = 0
while i<3:
print("当前是第%d次执行循环"%(i+1))
print("i=%d"%i)
i+=1
当前是第1次执行循环 i=0 当前是第2次执行循环 i=1 当前是第3次执行循环 i=2
while死循环实例代码如下:
# while True:
# print("这是一个死循环")
while循环计算1~100之间偶数的累积和(包含1和100),代码如下:
#第1章/xunhuan.py
i = 1
sum = 0
while i<=100:
if i%2 == 0:
sum = sum + i
i+=1
print("1~100的累积和为:%d"%sum)
1~100的累积和为:2550
while嵌套循环实现九九乘法表,代码如下:
#第1章/xunhuan.py
i = 1
while i<=9:
j=1
while j<=i:
print("%d*%d=%-2d "%(i,j,i*j),end='')
j+=1
print('\n')
i+=1
1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
像while循环一样,for也可以完成循环的功能。 而且,在Python中for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。所以相较于while循环,for循环更常用一些。 for循环命令如下:
for 临时变量 in 列表或者字符串等:
循环满足条件时执行的代码
for循环实例1代码如下:
# 循环对象为字符串
name = 'VenusAI'
for x in name:
print(x)
V e n u s A I
for循环实例2代码如下:
# 循环对象为列表
lst = [1,2,3,4,5,6,7]
for x in lst:
print(x)
1 2 3 4 5 6 7
for循环实例3代码如下:
# for循环可以配合python内置函数range()使用,来定义包含代码块的重复执行次数
for x in range(4):
print(x)
0 1 2 3
for循环小考题:有1、2、3、4这四个数字,能组成多少个互不相同且无重复数字的三位数?分别是什么?代码如下:
#第1章/xunhuan.py
count=0
L=[]
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
if a!=b and b!=c and a!=c:
count+=1
L.append(a*100+b*10+c)
print('满足条件的数字有{}个:{}'.format(count,L))
满足条件的数字有24个:[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
break语句用来结束整个循环,代码如下:
#第1章/xunhuan.py
name = '12345'
for x in name:
if x == '4':
break
print(x)
1 2 3
continue语句用来结束本次循环,紧接着执行下一次的循环,代码如下:
#第1章/xunhuan.py
name = '12345'
for x in name:
if x == '4':
continue
print(x)
1 2 3 5
注意: (1)break/continue只能用在循环中,除此以外不能单独使用。 (2)break/continue在嵌套循环中,只对最近的一层循环起作用。