Python文件不能保存高分

时间:2017-10-25 18:05:52

标签: python

我正在尝试制作一个数字猜谜游戏来练习我的编码。一切都有效,除非我重新开始游戏时没有保存我的高分,有什么建议吗?

print('Can you guess the number on the first try (hint: its inbetween 1-100)?')

import random
randomNum = random.randint(0,100)

userNum = 0
guesses = 0
userHigh = 0

gFile = open("score.txt", "r") #tells the score
gFile.read()
int(guesses)
print("the previous high score was", userHigh)
gFile.close()


while randomNum != userNum:
    try:

        userNum=int(input("What is your guess?: "))
        if randomNum>userNum:
            print('Higher')
        elif randomNum<userNum:
            print('Lower')

    except:
        print("please entera numeric value")
    else:
            guesses+=1

print("You win! The number was", randomNum)
print("You took {} guesses!".format(guesses))

gFile = open("score.txt", "w")
gFile.write(str(guesses))
gFile.close()

2 个答案:

答案 0 :(得分:1)

你永远不会更新userHigh var,试试这个:

userNum = 0
guesses = 0
userHigh = 0

gFile = open("score.txt", "r") #tells the score
h = gFile.read()
if h is not None:
   userHigh = h #update UserHigh
int(guesses)
print("the previous high score was", userHigh)
gFile.close()

答案 1 :(得分:0)

  

print("the previous high score was", userHigh)

当然你总是'0',因为你没有将值存储在变量userHigh上。 运行函数gFile.read()时,必须将值存储在userHigh var中,如下所示:

userHigh = gFile.read()

如果你不这样做,你就是在执行这个功能。 此外,我必须补充说,该程序不存储高分,只是存储任何分数。 要仅存储高分,您必须这样做:

if userHigh < guesses:
    gFile = open("score.txt", w)
    gFile.write(str(guesses))
    gFile.close()