3.编写程序,实现猜数小游戏。随机生成一个0~20(包括0和20)的数字,从控制台输入猜测的数字,输出提示太大还是太小,继续猜测,直到猜到为止,游戏过程中,记录猜对所需的次数,游戏结束后公布结果。
时间: 2024-10-12 16:16:24 浏览: 41
编写一个简单的猜数小游戏的Python代码示例如下:
```python
import random
def generate_random_number():
return random.randint(0, 20)
def guess_the_number():
number_to_guess = generate_random_number()
attempts = 0
print("欢迎来到猜数游戏!我会想好一个0到20之间的整数,你有5次机会猜测。")
while True:
attempt = int(input("请输入你猜的数字:"))
attempts += 1
if attempt < number_to_guess:
print("你猜的数字太小了!")
elif attempt > number_to_guess:
print("你猜的数字太大了!")
else:
break
print(f"恭喜你,你在第{attempts}次尝试就猜到了!你想猜的数字是 {number_to_guess}.")
guess_the_number()
```
在这个程序中,我们首先导入random模块来生成随机数。`generate_random_number`函数负责创建一个随机数,而`guess_the_number`函数则是游戏的主要流程,它会循环接收用户输入并给出提示,直到玩家猜中为止。游戏允许最多5次猜测,并在结束时显示猜对所需次数。
阅读全文
相关推荐



















