首页 > 解决方案 > 为什么有必要澄清我的变量在这种情况下是全局的?

问题描述

所以我拼凑了一个家务分配程序。每次你运行它时,它都会随机分配我和我室友之间的家务活。没有一个家务会连续超过 2 周分配给同一个人。无论如何,我很难让它工作,因为这是我的第一个 python 项目,但我认为它现在运行完美。

我的问题是,在我的 choreAssign() 函数中,如果我没有将我的变量澄清为全局变量,我会在第 50-55 行得到一个“未解决的引用”错误。这是为什么?(请记住,我还是新手/正在学习,我的所有研究都没有给出明显的答案)。

整个代码如下。代码中的一个很大的注释是澄清第 50 行的开始位置。我的代码相对较短,所以我认为可以发布整个内容。这是我在这个网站(或任何类似的网站)上的第一篇文章,所以如果缺少一些礼仪,我很抱歉。

import random

chores = ("Shower", "Kitchen counters", "Floors", "Toilet", "Mirror and Sink", "Tables/Laundry", "Garden", "Fan")

# Chore lists to be assigned this week
nick_chores1 = []
raul_chores1 = []
# Chore list for last week
nick_chores2 = []
raul_chores2 = []
# Chore list for week before last
nick_chores3 = []
raul_chores3 = []
# Extra chores that have already been repeated the last two weeks
chores_extra = []


def choreAssign():
    # GLOBAL VALUES IN QUESTION
    global nick_chores3
    global nick_chores2
    global raul_chores3
    global raul_chores2

    local_chores = list(chores)

    y = len(local_chores)
    while len(nick_chores1) < y / 2:
        random_chore = random.choice(local_chores)
        if len(nick_chores3) > 0:
            if nick_chores2.count(random_chore) + nick_chores3.count(random_chore) < 2:
                nick_chores1.append(random_chore)
                local_chores.remove(random_chore)
            else:
                chores_extra.append(random_chore)
                local_chores.remove(random_chore)
        else:
            nick_chores1.append(random_chore)
            local_chores.remove(random_chore)

    print(chores_extra)
    raul_chores1.extend(local_chores)
    raul_chores1.extend(chores_extra)
    local_chores.clear()
    chores_extra.clear()

    print("Nick's chores for the week are: " + str(nick_chores1))
    print("Raul's chores for the week are: " + str(raul_chores1))


# LINE 50 STARTS AFTER THESE COMMENTS. The below comment just clarifies what I'm trying to do with these few lines of code
    # the below 6 lines move the weekly data back one week (ex week 2 moves to week 3)

    nick_chores3 = nick_chores2[:]
    raul_chores3 = raul_chores2[:]
    nick_chores2 = nick_chores1[:]
    raul_chores2 = raul_chores1[:]
    nick_chores1.clear()
    raul_chores1.clear()

    x = input('Type "New" to assign a new weeks worth of chores: ').upper()
    if x == "NEW":
        choreAssign()


choreAssign()

标签: python-3.xvariables

解决方案


因为函数内部的变量只存在于函数结束之前。将它们声明为全局允许它们被保存而不是垃圾收集。如果您想拥有具有不同属性的不同对象或方法等,这很有用。如果您不想使用全局,您可以创建一个类,将要在方法/类之外使用的变量声明为该类的属性。如果您需要进一步解释,请发表评论:)


推荐阅读