Brendan Bruggeman
Brendan Bruggeman

Reputation: 1

Python file not saving high score

I am currently trying to make a number guessing game to practice my coding. Everything works except for the fact it is not saving my high score when I restart the game, any suggestions?

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()

Upvotes: 0

Views: 182

Answers (2)

sp________
sp________

Reputation: 2645

you never update the userHigh var, try this:

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()

Upvotes: 1

L00P3R
L00P3R

Reputation: 75

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

Of course you are getting always '0', because you aren't storing the value on the variable userHigh. When you run the function gFile.read(), you have to store the value on the userHigh var, like this:

userHigh = gFile.read()

If you don't do that, you are just executing the function. Also I must add that the program isn't storing the high score, is just storing whatever score. For storing only the high score you must do this:

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

Upvotes: 0

Related Questions