首页 > 解决方案 > Python:尝试在函数内引用和使用我在脚本顶部声明的变量时出现未解析的引用(变量名)

问题描述

我在 python 脚本的开头声明了这些变量:

hours = 0
mins = 0
secs = 0

然后我创建一个函数,并希望在我的函数中使用这些变量:

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

但它在赋值运算符 (=) 之后用红色强调了小时、分钟和秒,并表示“未解决的参考:小时”,分钟和秒也是如此。

如何在函数中使用在脚本顶部声明的变量?

谢谢。

编辑:有人告诉我将“全局时间”放在函数定义中。但是对于我刚刚定义的另一个函数,我不必这样做,变量“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!")

为什么我不需要在这个函数中这样做?

标签: python-3.x

解决方案


# 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

根据要求的其他示例:

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

推荐阅读