它正在打開一個 txt 檔案并寫入所詢問的內容。但不會在第一次列印結果。當我再次運行程式時,會列印第一次運行時存盤在 txt 檔案中的結果。
為什么它會在第一次運行時列印第一次運行的結果。
剛出道。
隨機匯入
print("======WELCOME TO THE DICE GUESSING GAME=======")
print("Rules of the game : - You can try 3 times!")
print("")
dice = random.randint(1, 6)
guesses = 3`enter code here`
file = open("score.txt", "a")
file.write("Dice number: " str(dice) " ")
while guesses > 0:
guess = int(input("guess the number of the dice: "))
file.write("guess = " str(guess) " ")
if dice == guess:
print("That is the correct answer!")
print("You have won the game!")
break
elif guesses != 1:
print("Try again! You have " str(guesses - 1) " chances left, good luck! ")
guesses -= 1
else:
print("You did not guess the correct number!")
print("The correct number was: " str(dice))
break
content = open("score.txt", "r")
read = content.read()
print(read)
file.close()
uj5u.com熱心網友回復:
您需要file在從句柄讀回檔案之前關閉content句柄,因為檔案輸出是緩沖的。
下面是 while 回圈后的代碼:
file.close()
content = open("score.txt", "r")
read = content.read()
print(read)
content.close()
uj5u.com熱心網友回復:
替代解決方案:使用
file.flush()
在寫完所有內容而不是關閉檔案之后
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401833.html
標籤:Python
