我将此代码作为大型骰子游戏程序的一部分,用于将高分保存在一个单独的文件(以及正常的获胜得分文件)中,但它始终保存高分,无论它是高是低。要么将其保存在Winning_scores文件中 它还将其保存为('Name:','John','Score:','10','\ n')的形式,而不是因为 str 而单独保存变量,否则我得到' write()参数必须是str,而不是元组',我也不太确定如何解决
tot1 = 5
tot2 = 1
name1 = ('John')
while True: #Code to find & print the winner
if tot1 > tot2:
print("Player 1 is the winner!")
#Opens file & appends the winning score at the end of it
tot1 = str(tot1)#Turns the score into a str
win_score = open("Winning_scores.txt", "a")
winner = ("Name: "+name1+" Score: "+tot1)
win_score.write(winner)
win_score.write("\n")
win_score.close()
print("Score saved.")
hisc = open("Winning_scores.txt", "w+")
highscore = hisc.read()
highscore_in_no = (highscore)
highscore_in_no = highscore_in_no
if tot1 > highscore_in_no:
print("Exceeded high score.")
highscore_in_no = tot1
hiscore = open("High_scores.txt", "a")
winner = ("Name: ",name1,"Score: ",tot1,"\n")
hiscore.write(winner)
hiscore.close()
print("High score saved.")
break
答案 0 :(得分:0)
这是您的问题:
one = "foo"
two = "bar"
this_is_a_tuple = (one, two)
this_is_also_a_tuple = (one)
this_is_not_a_tuple = one + two
this_is_a_tuple = (one + two)
在Python中用括号将值包装起来时,就是说它是一个 tuple ,类似于列表。这是一个希望更清晰的例子
;Connection Timeout=120;
答案 1 :(得分:0)
您的获胜者变量是一个元组,而不是字符串。
为了使用hiscore.write(winner)
,获胜者应为以下字符串:
winner = "Name: " + name1 + "Score: " + tot1 + "\n"
或更易读:
winner = "Name: {name1} Score: {tot1}\n".format(**locals())
您还可以将现有的获胜者元组加入字符串:
hiscore.write(' '.join(winner))