我的主要功能中未定义的词典

时间:2018-03-23 13:09:57

标签: python

def monday_availability(openhours_M): #openhours_M = number hours pool is open
hourone = int(input('Input the first hour in the range of hours the guard can work'))
hourlast = int(input('Input the last hour in the range of hours the guard'))
hour = 1
availability_M = []
while hour <= openhours_M:
    if hour >= hourone & hour <= hourlast:
        availability_M.append(1)
    else:
        availability_M.append(0)
return availability_M

上面是一个收集救生员可用性的函数,并且存储一个警卫可以在可用性列表中作为1工作的小时,或者如果他们不能,则存储0。我返回此列表的目的是将其添加到下面函数中的字典中。

def guard_availability(guards, openhours_M, openhours_T, openhours_W, 
openhours_R, openhours_F, openhours_S, openhours_Su):
continueon = 1
while continueon == 1:
    name = input('Input guards name of lifeguard to update availability' )
    availability = {}
    days = {}

    if openhours_M != 0:
        monday_availability(openhours_M)
    if openhours_T != 0:
        tuesday_availability(openhours_T)
    if openhours_W != 0:
        wednesday_availability(openhours_W)
    if openhours_R != 0:
        thursday_availability(openhours_R)
    if openhours_F != 0:
        friday_availability(openhours_F)
    if openhours_S != 0:
        saturday_availability(openhours_S)
    if openhours_Su != 0:
        sunday_availability(openhours_Su)

    days['Monday'] = availability_M
    days['Tuesday'] = availability_T
    days['Wednesday'] = availability_W
    days['Thursday'] = availability_R
    days['Friday'] = availability_F
    days['Saturday'] = availability_S
    days['Sunday'] = availability_Su
    availability[name]= days
    continueon = input('Enter 1 to add availability for another guard, 0 to stop: ')

return days

当我运行此代码时,我收到一条错误,说明我的可用性列表未定义,即使我在上面的函数中返回它们。我对返回函数的理解错误在哪里,以及如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

您可以在函数中返回dic值,但不要将其分配给任何变量。你应该这样做:

if openhours_M != 0:
    availability_M=monday_availability(openhours_M)
if openhours_T != 0:
    availability_T=tuesday_availability(openhours_T)
if openhours_W != 0:
    availability_W=wednesday_availability(openhours_W)
if openhours_R != 0:
    availability_R=thursday_availability(openhours_R)
if openhours_F != 0:
    availability_F=friday_availability(openhours_F)
if openhours_S != 0:
    availability_S=saturday_availability(openhours_S)
if openhours_Su != 0:
    availability_Su=sunday_availability(openhours_Su)

答案 1 :(得分:0)

monday_availability(openhours_M) 返回值。

返回变量不会将其分配给该函数范围之外的任何内容。

如果您重命名return availability_M以使用return foo并仅相应地更新该功能中的其他用途,那么错误会更有意义吗?

现在,实际捕获结果

 availability_M =  monday_availability(openhours_M)

甚至只是

days['Monday'] = monday_availability(openhours_M)

此外,没有看到该功能与星期一有什么关系。 Try to write DRY code