Eskimo4
Eskimo4

Reputation: 13

Python: Unresolved Reference (variableName) when trying to refer to and use variables I declared at the top of the script, within a function

I declare these variables at the start of my python script:

hours = 0
mins = 0
secs = 0

Then I create a function, and want to make use of those variables within my function:

def calc_running_total():
    hours = hours + int(running_total[0:2])
    mins = mins + int(running_total[3:5])
    if mins == 60 or mins > 60:
        hours += 1
        mins = mins - 60
    secs = secs + int(running_total[6:8])
    if secs == 60 or secs > 60:
        mins += 1
        secs = secs - 60

But it underlines hours, mins and secs after the assignment operator (=) in red, and says "Unresolved reference: Hours" and same for mins and secs.

How do I make use of variables declared at the top of my script within functions?

Thanks.

EDIT: I've been told to put "global hours" within the function definition. But I don't have to do that for another function I've just defined, with variable "activity_type":

def add_to_correct_list():
    if activity_type.casefold() == "work":
        if day_and_date:
            work_list.append((day_and_date))
            print(f"\n{day_and_date} added to work_list")
        work_list.append(activity_item_name + ": " + running_total)
        print("\nItem and time tracking added to Work_List!")

Why don't I need to do that in this function?

Upvotes: 1

Views: 94

Answers (1)

Alec
Alec

Reputation: 135

# these are considered 'global vars'
hours = 0
mins = 0
secs = 0


def calc_running_total():
    global hours  # now the method will reference the global vars
    global mins
    global secs
    hours = hours + int(running_total[0:2])
    mins = mins + int(running_total[3:5])
    if mins == 60 or mins > 60:
        hours += 1
        mins = mins - 60
    secs = secs + int(running_total[6:8])
    if secs == 60 or secs > 60:
        mins += 1
        secs = secs - 60

Other examples as requested:

hours = 1
def implicit_global():
    print(hours)  # 1
hours = 1
def point_to_global():
    global hours
    print(hours)  # 1
    print(hours+ 1)  # 2

print(hours)  # 2
hours = 1
def implicit_global_to_local():
    local_hours = hours  # copies the global var and sets as a local var
    print(local_hours)  # 1
    print(local_hours + 1)  # 2

print(hours)  # 1

Upvotes: 2

Related Questions