Why does python shows UnboundLocalError: local variable 'w' referenced before assignment?

Question:

from datetime import datetime
now = datetime.now()
q = int(now.strftime('%I'))
w = int(now.strftime('%M'))

def correct_time(time_diff):

    if w < (120 - time_diff):
        q = q + 1 
        w = w + (time_diff - 60)
    else:
        q = q + 2 
        w = w + time_diff - 120

    return q, w

correct_time(105)

#gives the error - UnboundLocalError: local variable 'w' referenced before assignment

In the above code I imported datetime module and assigned two varibles q and w (as seen in lines 3 and 4 of code). But on calling the function ‘correct_time()’ the Jupyter notebook gives an UnboundLocalError message.

According to what I have seen while creating a function before, in python a function can use a variable called before and outside the function. Since the variables q and w have already been defined why won’t it get recognized inside the function?

Asked By: aymusbond

||

Answers:

In the function correct_time, you assign to w so it is defined as a local variable.

However, before you assign to w, you check if w < (120 - time_diff):

At this point, w is not bound to anything, which gives you that error. You should instead either

A. Define q and w inside correct_time, or
B. Parameterize q and w and pass it in in the function call like correct_time(105, q, w)

Answered By: Adam Smith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.