【发布时间】:2020-10-01 19:13:19
【问题描述】:
所以我拼凑了一个家务分配程序。每次你运行它时,它都会随机分配我和我室友之间的家务活。没有一个家务会连续超过 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.x variables