while循环
while 条件:
条件满足时,做的事
....
处理条件(计数器+1)
举例:
i = 0
while i < 3:
print("Hello world!")
i += 1
//输出结果
Hello world!
Hello world!
Hello world!
赋值运算符
= 赋值
+= a+=b -> a=a+b
-= a-=b -> a=a-b
= a=b -> a=a*b /= a/=b -> a=a/b //= a//=b -> a=a//b %= a%=b -> a=a%b
**= a**=b -> a=a**b
举例:累加
i = 0
result = 0
while i < 100:
i += 1
result += i
print(result)
//输出结果:5050
偶数求和:
i = 0
result = 0
while i <= 100:
if i % 2 == 0:
result += i
i += 1
print(result)
//输出结果:2550
break与continue
break:
某一条件满足时,退出循环,不再执行后面的代码
continue:
某一条件满足时,不执行后续重复的代码
循环嵌套
while嵌套:
while 条件1:
条件满足做的事情
...
while 条件2:
条件满足做的事情
...
处理条件2
处理条件1
打印小星星:
i = 1
while i <= 5:
col = 1
while col <= i:
print("*" , end="")
col += 1
print("")
i += 1
//输出结果
*
**
***
****
*****
九九乘法表:
row = 1
while row <= 9:
col = 1
while col <= row:
print("%d x %d = %d" % (row, col, row * col), end="\t")
col += 1
print("")
row += 1
//输出结果:
1 x 1 = 1
2 x 1 = 2 2 x 2 = 4
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49
8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64
9 x 1 = 9 9 x 2 = 18 9 x 3 = 27 9 x 4 = 36 9 x 5 = 45 9 x 6 = 54 9 x 7 = 63 9 x 8 = 72 9 x 9 = 81
for循环
for 变量 in range(10):
循环需要执行的代码
else:
循环结束时,需要执行的代码
range用法
range(stop): 0~stop-1
range(start,stop): start~stop-1
range(start,stop,step): start~stop step(步长)