Adamso
Adamso

Reputation: 107

local variable referenced before assignment. python

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.

Upvotes: 2

Views: 638

Answers (2)

heemayl
heemayl

Reputation: 41987

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

Upvotes: 2

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

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

Upvotes: 0

Related Questions