Python 用文件保存游戏(1)

本文介绍了一个简单的猜数字游戏程序,程序会记录玩家的游戏次数、最少猜测次数及平均猜测次数,并显示这些统计信息。玩家需要根据提示猜测由程序随机生成的1到100之间的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from random import randint

#读取文件中的成绩数据
f=open('game.txt')
score=f.read().split()

#分别存入变量中
game_times=int(score[0])
min_times=int(score[1])
total_times=int(score[2])

#计算游戏的平均轮数,注意浮点数和避免除零错误
if game_times>0:
    avg_times=float(total_times)/game_times
else:
    avg_times=0
    
#输出成绩信息,平均轮数保留2位小数
print '你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案'%(game_times,min_times,avg_times)

num=randint(1,100)

print 'Guess what I think?'
bingo =False

while bingo==False:
    answer = input()

    if answer<num:
        print '%d is too small!'%answer #这里代的是answer

    if answer>num:
        print '%d is too big!'%answer

    if answer==num:
        print 'Bingo,%d is the right answer!'%num
        bingo=True


结果:

你已经玩了4次,最少0轮猜出答案,平均7.75轮猜出答案
Guess what I think?
1
1 is too small!
67
67 is too big!
34
34 is too small!
65
65 is too big!
56
56 is too big!
48
48 is too small!
50
50 is too small!
54
Bingo,54 is the right answer!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值