python 猜数字游戏(使用random模块完成)电脑随机一个范围内的数,用户输入数据判断,如果数大了,提供”数大了“,成功之后,加上用户是否继续功能。
时间: 2024-05-15 16:17:58 浏览: 88
好的,我知道你的要求了。下面是 Python 猜数字游戏的代码(使用 random 模块完成):
```python
import random
while True:
# 生成 1 到 100 之间的随机数
target = random.randint(1, 100)
print('电脑已经随机了一个数字,请开始猜数:')
while True:
# 用户输入猜测的数字
num = int(input())
if num < target:
print('你猜的数太小了,请重新输入:')
elif num > target:
print('你猜的数太大了,请重新输入:')
else:
print('恭喜你,猜对了!')
break
# 询问用户是否继续
print('是否要继续玩猜数字游戏?继续请输入 y,结束请输入其他任意字符:')
choice = input()
if choice != 'y':
break
```
这个程序中,我们使用了两个 while 循环:外层循环用于控制程序是否继续运行,内层循环用于让用户多次猜数字,直到猜中为止。程序开始的时候会生成一个 1 到 100 之间的随机数,然后在内层循环中不断询问用户猜测的数字,如果猜测的数字和随机数相等,那么就输出恭喜信息,内层循环结束。
接下来,我们会询问用户是否要继续玩游戏。如果用户输入的是 y,那么外层循环会继续执行,程序会重新生成一个随机数,内层循环也会重新开始。如果用户输入的不是 y,那么外层循环结束,程序退出。
阅读全文
相关推荐
















