0
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?

aymusbond
  • 161
  • 3
  • 14
  • 3
    You're assigning a local `w` variable, and attempting to read from a global `w`. Since that doesn't make any sense, the Python interpreter assumes you're making an error, and wanted a local `w`, and says `UnboundLocalError`. If you want to use a global `w`, add the line `global w` to the start of the function. – Alex Huszagh Aug 25 '19 at 07:10
  • 1
    ...but keep in mind that globals are generally Bad, and definitely code smell. Avoid them if possible (and here it appears like it is!) – Adam Smith Aug 25 '19 at 07:17

1 Answers1

3

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)

Adam Smith
  • 52,157
  • 12
  • 73
  • 112