1.死循环和无限循环的异同
死循环 | 无限循环 | |
---|---|---|
相同点 | 在程序执⾏层⾯上看起来是⼀样的, 都是代码⼀直执行不能停止 | |
不同点 |
|
|
2.break与continue的区别
关键字 break | 关键字 continue | |
---|---|---|
相同点 |
| |
不同点 |
|
|
3.循环版本的石头剪刀布
1, 只需要确定哪些代码需要重复执⾏
2, 将需要重复执⾏的代码 写在循环的缩进中(循环体)
(1)使用continue结束本次循环
# 分析:
# 1. 控制台出拳(⽯头1/剪⼑2/布3) player = input()
# 2. 电脑出拳 computer = 电脑的结果
# 3. 判断胜负
# 3.1 玩家胜利
# 3.1.1 玩家出⽯头, 电脑出剪⼑ player == 1 and computer == 2
# or
# 3.1.2 玩家出剪⼑, 电脑出 布 player == 2 and computer == 3
# or
# 3.1.3 玩家出布, 电脑出 ⽯头 player == 3 and computer == 1
# 3.2 平局 玩家和电脑出的内容⼀样, player == cpmputer
# 3.3 电脑胜利 else:
import random
while True:
player = int(input('请出拳 石头1/剪刀2/布3/退出0:'))
if player == 0:
continue # 结束本次循环,继续下一次循环
# print("欢迎下次游戏!")
# break
computer = random.randint(1, 3)
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("玩家胜利!")
elif player == computer:
print("平局!")
else:
print("电脑胜利!")
(2)使用break终止整个循环
# 分析:
# 1. 控制台出拳(⽯头1/剪⼑2/布3) player = input()
# 2. 电脑出拳 computer = 电脑的结果
# 3. 判断胜负
# 3.1 玩家胜利
# 3.1.1 玩家出⽯头, 电脑出剪⼑ player == 1 and computer == 2
# or
# 3.1.2 玩家出剪⼑, 电脑出 布 player == 2 and computer == 3
# or
# 3.1.3 玩家出布, 电脑出 ⽯头 player == 3 and computer == 1
# 3.2 平局 玩家和电脑出的内容⼀样, player == cpmputer
# 3.3 电脑胜利 else:
import random
while True:
player = int(input('请出拳 石头1/剪刀2/布3/退出0:'))
if player == 0:
# continue # 结束本次循环,继续下一次循环
print("欢迎下次游戏!")
break
computer = random.randint(1, 3)
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("玩家胜利!")
elif player == computer:
print("平局!")
else:
print("电脑胜利!")
(3)在以上基础上,添加代码实现:如果玩家赢三次,就结束循环
import random
n = 0
while n < 3:
player = int(input('请出拳 石头1/剪刀2/布3/退出0:'))
if player == 0:
# continue # 结束本次循环,继续下一次循环
print("欢迎下次游戏!")
break
computer = random.randint(1, 3)
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("玩家胜利!")
n = n + 1
elif player == computer:
print("平局!")
else:
print("电脑胜利!")
或
import random
n = 0
while True:
player = int(input('请出拳 石头1/剪刀2/布3/退出0:'))
if player == 0:
# continue # 结束本次循环,继续下一次循环
print("欢迎下次游戏!")
break
computer = random.randint(1, 3)
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("玩家胜利!")
n = n + 1
if n == 3:
print("您已胜利三次,游戏结束!")
break
elif player == computer:
print("平局!")
else:
print("电脑胜利!")
4.求 1- 100 之间的累加和
1 + 2 + 3 + ... + 99 + 100使⽤循环产⽣ 1-100 之间的数字
n = 1
sum = 0 # 定义变量 保存求和的结果
while n <= 100:
sum += n # 0 + 1 + 2 + 3 + ... + 100
n += 1
print(f'1-100的和为{sum}') # 求和的结果 只需要打印⼀次, 所以放在循环的外边
未完待续。。。