Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
this is the question:

The game() function in a program lets a user play a game and returns the score as an integer. You need to read a file"hiscore.txt" which is either blank or contains the previous high score. You need to write a program to update the high score whenever someone breaks the high score.


This is the code i have typed:

Python

file=open("hiscore.txt","r")
c=file.read()
score=int(c)
file.close()

new_score=int(input("Enter ur new score"))
if score<new_score:
    file=open("hiscore","w")
    file.write(c)




The error is given below:

Traceback (most recent call last):
File "d:\python\blah.py", line 3, in <module>
score=int(c)
ValueError: invalid literal for int() with base 10: ''

What I have tried:

This is the code i have typed:

<pre lang="Python">
file=open("hiscore.txt","r")
c=file.read()
score=int(c)
file.close()

new_score=int(input("Enter ur new score"))
if score<new_score:
    file=open("hiscore","w")
    file.write(c)
Posted
Updated 17-Jul-22 3:12am

1 solution

c does not contain an integer - which means that the file doesn't either, it is empty, or it has additional information in it.

Start by looking at the file and what it contains - Notepad is a good start here.
Then if that looks right, use the debugger to find out exactly what c contains.

What I'd suggest is that you write your file with something like "Hiscore=" and then the number. You can then look for the "=" when you read it back and only process the number data after it if you find it.

Just makes the file a bit more "user friendly" and it's easier for your code to spot when the high score isn't actually there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900