Python Forum
Newbie - code solution explained
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie - code solution explained
#1
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
'''
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.
Reply
#2
Please wrap code in Python tags to retain indentation. There is a button in the editor for doing this.

try/except catches the IOError exception that is raised if userScores.txt cannot be opened for reading. If the IOError occurs, execution jumps to the code block under the "except IOError:", otherwise it executes the remaining code in the "try:" block.

I do not like how the file read is handled. The code depends on each "line" having multiple fields that are separated by commas. That is what the "split" does. It takes a str read from the file and splits it into a list of a substrings.
words = "The quick brown fox jumped over the lazy dog".split(' ')
print(words)
Output:
['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
If the file contains a blank line or a line without any commas, contents[1] will raise an index error. I would test for this.
'''Read userName's score from the score file.  Return score if found
    else None.
    
    Create score file if it doesn't exist
    '''
    try:
        with open('userScores.txt', 'r') as file:
            for line in file:
                content = line.split(', ')
                if len(content) > 1 and content[0] == userName:
                    return content[1]
    except IOError:
        print("File not found. A new file will be created.")
        open('userScores.txt', 'w').close()
    return None
This code contains a check to make sure the index error does not happen. If content does not have at least two items, the content[0] == userName test is skipped.

I also changed the code to use a context manager. Notice that I don't "close" the file anywhere. By using the context manager "with open('userScores.txt', 'r') as file:" the file is closed automatically when execution leaves the block of code inside the context. It doesn't matter if the reason is because I reach the end of the file or if I return the score, or even if there is an error that raises an exception. Context managers are the preferred way to work with files.

When you open a file for reading, Python returns a file object. The file object is an iterator (like range(10) for example), so it can be used in a for loop to get "input" from the file.

A few comments about the function.

I find it odd to return -1 if you did not find a score. I guess there is no possibility of negative scores, but why not return None. None is provided for exactly this purpose, to have a value that means "I don't have a value".

This function supposedly returns a score, but it actually returns a str. The str may be the string representation of a number, but it is not a number. The user of this function will have to convert the return value to a float or int if they want a number. I would consider doing the conversion in the function and returning a number instead of a str.
Reply
#3
Hi,

thank you for your advice on posting code and your detailed reply.
I appreciate your advice and will have a play about with this.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  newbie question - can't make code work tronic72 2 693 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Python Tutorial 4.4 Loop Explained rts 2 863 Sep-26-2022, 07:46 PM
Last Post: rts
  Sort Differences in 2.7 and 3.10 Explained dgrunwal 2 1,364 Apr-27-2022, 02:50 AM
Last Post: deanhystad
  please looking for typo in my code (solution please) jamie_01 1 1,275 Jan-12-2022, 06:45 AM
Last Post: Gribouillis
  Quick Help - Timers - Need Small Solution for Working Code EwH006 5 4,043 Nov-17-2020, 04:09 AM
Last Post: EwH006
  newbie need help update code Mariaa 3 2,085 Oct-02-2020, 08:12 AM
Last Post: ibreeden
  I am a newbie.Help me with this simple piece of code feynarun 3 2,814 Jan-08-2020, 12:40 PM
Last Post: perfringo
  complete newbie, trying to tweak some code notarobot 6 3,156 Nov-02-2019, 03:35 PM
Last Post: notarobot
  need solution to code mccluregamer4472 9 3,981 Mar-04-2019, 12:40 AM
Last Post: mccluregamer4472
  Help with a Code (Newbie) GamingC3 1 1,912 Aug-19-2018, 11:48 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020