循环
请思考: 找到所有水仙花数?
while 循环
语法
while 条件:
循环体
i = 1
while i<=10:
print(i)
i+=1
计算 1 ~100 的累加和
i = 1
sums = 0
while i<=100:
sums += i;
i+=1
print(f"sums = {sums}")
质数判断器
num = int(input('请输入一个大于1的自然数:'))
i = 2
count = 0
while i < num:
if num % i == 0:
count += 1
i += 1
if count == 0:
print(f'{num}是质数')
else:
print(f'{num}不是质数')
中断循环
break和continue
- break终止本层(当前层)循环
- continue终止本次循环(遇到continue之后的代码本次不会被执行了), 执行下一次循环
i = 0
sums = 0
while i <= 100:
if sums > 1000:
break
sums += i
i += 1
print(f"sums = {sums}")
print('--'*20)
i = 0
sums = 0
while i <= 100:
if i%2 == 0:
i += 1
continue
sums += i
i += 1
print(f'{sums}')
循环嵌套
循环里面还有循环(两层最常用)
while 条件1:
条件1成?执?的代码
......
while 条件2:
条件2成?执?的代码
......
外层循环负责打印多少行, 里侧循环负责当前行具体的情况
打印**
打印 5 x 6 的星星
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
i = 0
while i < 5:
j = 0
while j < 6:
print("* ", end='')
j += 1
print()
i += 1
*
* *
* * *
* * * *
* * * * *
* * * * * *
i = 0
while i < 6:
j = 0
while j <= i:
print("* ", end='')
j += 1
print()
i += 1
i = 1
while i <= 9:
j = 1
while j <= i:
print(f'{j} x {i} = {i*j}', end='\t')
j += 1
print()
i += 1
打印 2 ~ 100 之间所有的素数
num = 2
while num <= 100:
i = 2
count = 0
while i < num:
if num % i == 0:
count += 1
break
i += 1
if count == 0:
print(f'{num} ', end='')
num += 1
for 循环
for 临时变量 in 序列:
重复执?的代码1
重复执?的代码2
......
迭代序列
for i in 'eric':
print(i)
求累加和
sums = 0
for i in range(1, 101):
sums += i
print(sums)
break和continue
sums = 0
for i in range(1, 101):
if sums > 1000:
break
sums += i
print(sums)
sums = 0
for i in range(1, 101):
if i%2 == 0:
continue
sums += i
print(sums)
while else
while 条件:
条件成?重复执?的代码
else:
循环正常结束之后要执?的代码
所谓else指的是循环正常结束之后要执?的代码,即如果是break终?循环的情况,else下?缩进 的代码将不执?。因为continue是退出当前?次循环,继续下?次循环,所以该循环在continue控制下是可以正常 结束的,当循环结束后,则执?了else缩进的代码。
from random import randint
computer = randint(1, 100)
print(computer)
game_count = int(input("请投币"))
while game_count > 0:
num = int(input("请输入要猜的数字 1 ~ 100"))
game_count -= 1
if num > computer:
print("猜大了")
elif num < computer:
print("猜小了")
else:
print("恭喜你猜对了")
break
else:
print("你的币子用光了!!!")
for else
作业
完成 for 版本的 循环嵌套 for else 版本的猜数字游戏
|