It is opening an txt file and writes what is asked. But does not print the results on the first time.
When I run the program again, then the results that were stored in the txt file from the first run get printed.
Why does it nog print the results from the first run on the first run.
Just starting out.
import random
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()
>Solution :
You need to close the file handle before reading the file back in from the content handle, as file output is buffered.
Here is what the code should look like after the while loop:
file.close()
content = open("score.txt", "r")
read = content.read()
print(read)
content.close()