所以我终于成功地制作了它,这样我就可以从我的文本文件中读取并将其添加到列表中。但是现在我有一个小问题,每个值看起来像6\n。我需要重新构造我的代码吗。 下面是代码
错误:
Number guessing game with highscores.py", line 42, in <module>
highscoreS = [highscores.replace("\n", "") for highscores in highscoreS]
NameError: name 'highscoreS' is not defined
尽管我已经清楚地定义了它
from random import randint
a = True
n = randint(1,10)
guesses = 0
#If scores ever need to be reset just run function
def overwritefile():
f = open("Numbergame.txt", "w")
f.close()
#overwritefile()
#Guessing Game Code
while a == True:
guess = int(input("What is your guess? \nEnter a number!"))
if guess > n:
print("Guess is too high! \nTry Again!")
guesses += 1
elif guess < n:
print("Guess is too low! \nTry Again!")
guesses += 1
else:
guesses += 1
a = False
print("You guessed the number! \nIt was " + str(n) + "\nIt took you: " + str(guesses) + " guesses")
#Adding Score to the file
f = open("Numbergame.txt", "a")
f.write(str(guesses) + '\n')
f.close()
highscores = []
#Compare values and figure out if it is a new highscore
#Maybe I will use the TRY thing got taught recently might help iron out some errors
#f = open("Numbergame.txt").readlines()
with open('Numbergame.txt', 'rt') as f:
for highscore in f:
highscores.append(highscore)
highscoreS = [highscores.replace('\n', '') for highscores in highscoreS]
在使用它之前,您需要定义它。到目前为止,
highscoreS
在定义它的同一行中使用。正确的方法是先将所有值读入列表,然后使用您定义的列表要覆盖原始
highscores
,可以执行以下操作然而,这是不必要的复杂。与其这样做,我建议您在阅读分数时只需
strip()
空格您可能还希望将值转换为整数,在这种情况下,在从文件读取行时,在循环中也这样做是有意义的
如@tdelaney所述,您可以将其进一步浓缩为python列表理解:
相关问题 更多 >
编程相关推荐