while循环
while
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
......
i = 0
while i < 5:
print('媳妇儿,我错了')
i += 1
break和continue
退出循环的两种方式。
- break,表示终止循环
- continue, 表示跳出当次循环,执行下一次循环。
while嵌套
while English条件1:
条件1成立执行的代码
......
while 条件2:
条件2成立执行的代码
......
j = 0
while j < 3:
i = 0
while i < 3:
print('媳妇儿,我错了')
i += 1
print("刷晚饭的碗")
print('一套惩罚结束')
j += 1
while嵌套应用
- 打印一个正方形的号,每行5个一共5行
j = 0
while j < 5
i = 0
while i < 5:
print('*', end='')
i += 1
print()
j += 1
'''
*****
*****
*****
*****
'''
- 打印星号的个数与行号数相同
j = 0
while j < 5
i = 0
while i <= j:
print('*', end='')
i += 1
print()
j += 1
'''
*
**
***
****
*****
'''
- 九九乘法表
"""
1. 打印一个乘法表达式子:x * x = x*x
2. 一行打印多个表达式 -- 一行表达式的个数和行号相等 -- 循环: 一个表达式 -- 不换行
3. 打印多行表达式 -- 循环:一行表达式 -- 换行
"""
j = 1
while j <= 9:
i = 1
while i <= j
print(f'{i} * {j} = {i * j}', end = '\t')
i += 1
print()
j += 1
else
循环可以和else配合使用,else下方缩进的代码指的是当循环正常结束之后要执行的代码
while…else
while 条件:
条件成立重复执行的代码
else:
循环正常结束之后要执行的代码