Hi all,
I'm new to Python and working through a book with a project that has example solutions.
Project to create a Math/Binary game and exercise I'm currently on is to get a user score.
I'm trying to understand the for loop in code below:
'''
Getting user score
Solutions taken from book - understand program and comment
sja 8th Sept 2021
'''
My understanding of the variable 'content' is to define split of the user name and score using a comma?
How does the for loop then read the file?
What does content[0], content[1] and return '-1' actually do?
Any explanation of the code for deeper understanding would be greatly appreciated, thank you.
PS,
Is it preferred to attached code?
Regards,
Stephen
I'm new to Python and working through a book with a project that has example solutions.
Project to create a Math/Binary game and exercise I'm currently on is to get a user score.
I'm trying to understand the for loop in code below:
'''
Getting user score
Solutions taken from book - understand program and comment
sja 8th Sept 2021
'''
def getUserScore(userName): #define function to get a user score try: #check to see if user score text file exists input = open('userScores.txt', 'r') #open user score text file in variable input for line in input: #read each line in user score text file content = line.split(', ') if content[0] == userName: input.close() return content[1] input.close() return '-1' except IOError: #if no user score file exists - create one print("File not found. A new file will be created.") input = open('userScores.txt', 'w') #create text file for user score input.close() return '-1'Understand the try / except is to check for presence of user score txt file and create if it doesn't exist.
My understanding of the variable 'content' is to define split of the user name and score using a comma?
How does the for loop then read the file?
What does content[0], content[1] and return '-1' actually do?
Any explanation of the code for deeper understanding would be greatly appreciated, thank you.
PS,
Is it preferred to attached code?
Regards,
Stephen
Larz60+ write Sep-16-2021, 10:54 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
I have fixed your code this time. Please use bbcode tags on future posts.
Suggested by Deanhystad below.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
I have fixed your code this time. Please use bbcode tags on future posts.
Suggested by Deanhystad below.