2

i wrote the following function:

def get_running_time(test):
for line in PERFORMANCE_FILE:
    print(test_time)
    line_rr = line.split()
    test_time = int(line_rr[-2])
    print(test_time)
return test_time

and i get the error:

"local variable 'test_time' referenced before assignment"

i saw all of the solutions relay on globals but i dont want to use that. i tried using globals but it makes things more complicated for me because when i call the function "get running time" it does not consider the initialization of "test_time" in the beginning and the global remains the same number through out the entire running of the program. is there another way to solve this? thanks.

1
  • 1
    That is very odd. You should be getting IndentationError already at the for. ;) Commented Jul 22, 2018 at 15:27

2 Answers 2

2

The UnboundLocalError is because the iterator PERFOMANCE_FILE could be empty, in that case the iteration by for never happens, in that case test_time never gets set (as its being set inside the loop only).

But as you are returning test_time the UnboundLocalError is being raised. You can instead set a default at top to return when PERFOMANCE_FILE is empty:

def get_running_time(test):
    test_time = ''  # Default
    for line in PERFORMANCE_FILE:
        print(test_time)
        line_rr = line.split()
        test_time = int(line_rr[-2])
        print(test_time)
    return test_time
Sign up to request clarification or add additional context in comments.

2 Comments

now i get the error: test_time = int(line_rr[-2]) "IndexError: list index out of range"
@Adamso Thats a totally different thing. I'm gonna give you a hint -- len(line_rr) must be 1 for the line the error is being shown. And you need to catch the exception or check the list length beforehand.
0

Try this:

def get_running_time(test):
    for line in PERFORMANCE_FILE:
        #test_time is not defined here on the first loop so you can't print it
        line_rr = line.split()
        test_time = int(line_rr[-2])
        print(test_time)
    return test_time

1 Comment

Not quite. Check my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.