简体   繁体   中英

Return in python, reading values from .txt file

Level: beginner

Hey, i'm trying to resolve an exercise in Python.

The code is comparing userName given in function argument print(getUserPoint("Benny")) ,if that name exists in userScores.txt, i'd like to return user score, otherwise i'd like to return a string "-1".

If i use print a result is printed as expected, however if i use return , function always returns "-1", even if a userName exists in a file.

Looks like it reads only the first user, score values from the .txt file.

Can anybody please explain why "return" works that way in this case?

userScores.txt:

Ann, 100
Benny, 102
Carol, 214
Darren, 129

Code:

  try:
        def getUserPoint(userName):
            f = open("userScores.txt", "r")
            file = f.readlines()
            print(file)
            for item in file:
                print(item)
                content = item.split(',')
                if content[0] == userName:
                    f.close()
                    return content[1]
                    #print(content[1])
                else:
                    f.close()
                    return "-1"
                    #print("-1")
    except IOError:
        print("File not found")
        f = open("userScores.txt", "w")
        f.close()
        print("-1")

You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with , it's a much cleaner way to handle closing files:

def getUserPoint(userName):
    try:
        with open("userScores.txt", "r") as file:
            for item in file:
                print(item)
                content = item.split(',')
                if content[0] == userName:
                    return content[1]
            return "-1"
    except IOError:
        print("File not found")
        return "-1"

On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.

Eg If you call getUserPoint('Benny')

On the first iteration of the loop, it will compare "Ann" == "Benny"

This returns false , so the control goes to your else clause and return from the function - no more looping.

import os

def getUserPoint(userName):
    f=open('userScores.txt')
    file=f.readlines()
    for item in file:

        content=item.split(',')

        if content[0]==userName:
            f.close()
            return content[1]
        else:
            continue

    f.close()   
    print('UserNotfound')
    return '-1'

x=getUserPoint('Benny')
print(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM