Files
python-flask/project03/03.[任务书]流程控制练习.md
2025-09-11 16:52:33 +08:00

110 lines
3.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 猜数字小游戏
## 需求
- 编写一个猜数字游戏随机产生1~100之间的整数然后让用户输入猜的数字是什么
- 每次用户输入数字之后是错误的,都会进行提示,输入的数字偏大还是偏小
- 用户输入错误3次之后提示游戏结束并且退出程序
## 参考代码
```python
import random
# 产生随机数
num = random.randint(1, 100)
# 定义可以猜的次数
i = 3
# 开启循环,让用户输入数字,并且进行判断
while i:
i -= 1
guess = input("输入1~100之间的整数")
# 判断用户输入的时候是纯数字
if guess.isnumeric():
# 纯数字就可以进行类型转换
guess = int(guess)
else:
print("你输入的不是一个数字!")
continue
if(guess > num):
print(f"你猜大了,还有{i}次机会")
elif(guess < num):
print(f"你猜小了,还有{i}次机会")
else:
print("你猜对了")
break
print("游戏结束")
```
> <span style="color: red; background: yellow; padding: 2px 5px; font-size: 22px;">作业3.1提交的内容</span>
>
> - 程序运行成功的截图,单独发送给组长
## 完善石头剪刀布游戏
- 石头剪刀布游戏,让用户和计算机猜拳
- 实现三局两胜
## 参考代码
```python
import random
# 可选择的选项
options = ["石头", "剪子", "布"]
# 初始化得分
player_score = 0
computer_score = 0
win_required = 2 # 需要赢得的比赛局数
print("欢迎来到石头剪子布游戏!")
print("三局两胜制。")
print("请从以下选项中选择:")
for i, option in enumerate(options):
print(f"{i + 1}. {option}")
# 游戏主循环
while player_score < win_required and computer_score < win_required:
# 玩家选择
player_choice = int(input("请输入你的选择1-3")) - 1
# 计算机随机选择
computer_choice = random.randint(0, 2)
print(f"\n你选择了:{options[player_choice]}")
print(f"计算机选择了:{options[computer_choice]}")
# 判断胜负
if player_choice == computer_choice:
print("平局!")
elif (player_choice == 0 and computer_choice == 1) or \
(player_choice == 1 and computer_choice == 2) or \
(player_choice == 2 and computer_choice == 0):
print("你赢了!🎉")
player_score += 1
else:
print("你输了!😢")
computer_score += 1
# 检查是否已有胜者
if player_score == win_required:
print(f"恭喜你!你以 {player_score}{computer_score} 赢得了比赛。")
break
elif computer_score == win_required:
print(f"很遗憾,计算机以 {computer_score}{player_score} 赢得了比赛。")
break
# 游戏结束
print("游戏结束!感谢参与。")
```
> <span style="color: red; background: yellow; padding: 2px 5px; font-size: 22px;">作业3.2提交的内容</span>
>
> - 程序运行成功的截图,单独发送给组长