Created
October 2, 2021 18:58
-
-
Save ProbonoBonobo/5653669e80250c79221f8c8c1f542685 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" Simple example of a Python program that initializes and saves a persistent 'high score' variable | |
by reading/writing a value to a file. """ | |
high_score_file_name = "hiscore" | |
try: | |
with open(high_score_file_name, "r") as f: #open the file 'hiscore' in read mode | |
old_score = int(f.read()) | |
except FileNotFoundError: # if the 'hiscore' file does not exist... (e.g., no one has played the game yet) | |
old_score = 0 # initialize the old_score variable to default value (e.g., 0)... | |
print(f"File 'hiscore' not found. Creating it now...") # open the file 'hiscore' in write mode... | |
with open(high_score_file_name, "w") as f: | |
f.write(str(old_score)) #...and write it to the file. (not strictly necessary yet, but at this point we could now open | |
# the 'hiscore' file in this directory and examine its contents. It should now read '0' | |
new_score = int(input("Enter a number: ")) # our 'game' consists of accepting a numeric input from a player... | |
hi_score = max(new_score, old_score) # and setting the 'high score' variable to the highest value entered by any player of the game | |
with open(high_score_file_name, "w") as f: # finally, before exiting the program... open the 'hiscore' file in write mode... | |
f.write(str(hi_score)) # write the `hi_score` variable to a file (be sure to cast to string first -- our file descriptor object `f` expects an str type when opened in "w" mode) | |
print(f"The highest number is now: {hi_score}") # and print the new high score to the user. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment