Python 猜数字游戏:三局平均猜测次数统计

发布时间:2026/10/8 13:31:47
Python 猜数字游戏:三局平均猜测次数统计 import random猜测的次数和历史列表from idlelib import historydef one():# 生成数字answer random.randint(0, 100)# 建立空列表用来保存每一次猜的数字history []# 猜测次数计数器count 0while True:num int(input(“请输入你猜的数字(1~100)”))count 1if num answer:print(“大了”)elif num answer:print(“小了”)if num answer:print(“恭喜你猜中了”)print(f本局猜测记录{history}“)print(f本局猜了{count}次”)# 结束这一局的while循环return count记录3局的总次数total 0保存每局的结果for i in range(3):# 打印提示显示几局print(f\n—第{i1}局—)# 调用one()函数开始一局猜数字游戏本局猜测次数存入变量cc one()# 将猜测数累加到总次数totaltotal c三次的平均值avg total / 3输出平均值保留2位小数print(f\n平均次数{avg:.2f})