Skip to content Skip to sidebar Skip to footer

My Program Only Appends One User Input To List When Main Is Looped

This is part of my code for a guessing game. I want to count the guesses of a player, and then append their name and number of guesses to a list that is later written or appended t

Solution 1:

The 'w' mode overwrites highscore.txt. Think of it as deleting the file and then creating it all over again.

You want open('highscore.txt', 'a') to append, as described in https://docs.python.org/3/library/functions.html#open

EDIT:

Alternatively, perhaps you want to initialize highscore to the empty list outside the loop? (Your question is unclear. It would be helpful to replace the current code with valid python code, and to show example desired file output.)

As it stands, you loop many times, each time making the length of highscore zero, then appending so length is one, then you sort a single entry (no-op), then you write a one-line file. It isn't clear if you're trying to write e.g. a three-line file by interacting and looping three times, or by invoking the program from bash three separate times (in which case 'a' append would be appropriate). Help us out, and clarify the code and your intent.

Suppose Alice and Bob are playing. Perhaps instead of a list you would prefer to use a name_to_score dict, if you intend to overwrite Alice's score each time she plays again.

You don't show us the content of def choose but I assume it prompts Yes/No and returns True/False. You don't show us the content of def main but I assume that you do not want to invoke main() in the body of the loop, since the while choose(): loop probably suffices. Trying to read your mind doesn't always work well. Stating your problem more clearly would help us give more relevant answers.

Post a Comment for "My Program Only Appends One User Input To List When Main Is Looped"