Files
2025PY/day09/04-练习2.py
2025-05-22 16:50:44 +08:00

27 lines
1.0 KiB
Python
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.
# 2.猜年龄游戏
# 前面讲过一个random模块(内置模块,先导入,再使用)利用random对象下面的方法随机产生一个整数
# 2.1.准备随机数(randint)
# 2.2.通过无限循环去判断用户输入的是否是随机的年龄
# 用户输入的数字大了
# 用户输入的数字小了
# 用户输入的数字对了,结束循环(break)
# 2.3.需要设置变量统计猜测的次数,定输赢(迭代+= / -=)
import random
age = random.randint(1,200) # 生成1-200之间的数据包括1和200
count = 0 # 统计你猜测的次数的初始值
while True: # 无限循环来猜测,正确了就结束
my_age = int(input('请输入你猜测的数字:')) # 用户猜测的数字
count += 1 # 统计你猜测的次数
if my_age > age :
print('你输入的数字 大 了')
elif my_age < age :
print('你输入的数字 小 了')
else: # 注意:如果猜对了,结束循环
print(f'恭喜你,你猜对了!随机的年龄是{age},你总共猜测了{count}')
break # 结束循环