1. while 循环的基本使用方法
while 判断条件:
执行语句
条件成立:再次进入循环;
条件不成立:结束循环结构
#死循环案例:
i = 0
while i <= 10:
print(i)
死循环的几种情况:
1.打印变量,变量没有改变,满足不了结束循环的条件;
2.while True:避免条件不改变
i = 0
while i <= 5:
i += 1
print(i)
运行结果:
1
2
3
4
5
6
i = 0
while i <= 5:
print(i)
i += 1
0
1
2
3
4
5
注意以上两个while循环的区别
2. while循环中加入if
# 打印出10以内的3的倍数
n = 1
while n <= 10:
if n%3 == 0:
print('=====>',n)
n += 1
=====> 3
=====> 6
=====> 9
3. 利用while循环求累加和
利用while循环求20以内的累加和
i = 1
sum = 0
while i <= 20:
sum += i
i += 1
print(sum)
输出结果:
210
4. 打印出一个三角形
方法一:
while i <= 5:
print(i*'*')
i += 1
方法二:使用双层嵌套
i = 1
while i <= 5:
count = 1
while count <= i:
print('*',end='')
count += 1
i += 1
print()
输出结果:
*
**
***
****
*****