如何在函数中自动生成新变量?

时间:2017-10-26 01:07:34

标签: python global-variables

有没有办法可以在每次调用函数时存储函数的所有返回值?这是代码:

def workdaystart(dayoftheweek):
    starthour=input("What is your START HOUR for "+ dayoftheweek+"? ")
    print("Is that AM or PM")#Allows us to differentiate between time periods#
    print ("1. AM")
    print ("2. PM")
    print("3.I DONT WORK")
    starthoursuffix = int(input('Enter your choice [1-2] : '))

    if starthoursuffix == 1:

        starthour=starthour+"AM"
    elif starthoursuffix==2:
        starthour=starthour+"PM"
    else:
        starthour=" "
    return starthour
daysofweek=
    ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
for day in daysofweek:
    x=workdaystart(day)

正如您所看到的那样,它会运行函数列表中的项目,但我希望将当天的开始时间存储为功能之外的变量。

4 个答案:

答案 0 :(得分:1)

听起来你正在寻找一个将日名映射到开始时间的字典:

starthours = {}
for day in daysofweek:
    starthours[day] = workdaystart(day)

答案 1 :(得分:0)

我这样读了这个问题,你想把所有的开始时间存储在一个变量中,而对于你当前的代码,每次循环执行该函数时都会覆盖x。

如何使用字典?然后,您可以根据日期随时检索它。

def workdaystart(dayoftheweek):
    starthour=input("What is your START HOUR for "+ dayoftheweek+"? ")
    print("Is that AM or PM")#Allows us to differentiate between time periods#
    print ("1. AM")
    print ("2. PM")
    print("3.I DONT WORK")
    starthoursuffix = int(input('Enter your choice [1-2] : '))

    if starthoursuffix == 1:
        starthour=starthour+"AM"
    elif starthoursuffix==2:
        starthour=starthour+"PM"
    else:
        starthour=" "
    return starthour

daysofweek["monday",...]
workdaydictionary = {}

for day in daysofweek:
    workdaydictionary[day] = workdaystart(day)

答案 2 :(得分:0)

您可以生成返回的starthour值列表:

daysofweek = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
hours = [workdaystart(day) for day in daysofweek]

答案 3 :(得分:0)

Barmar的回答非常有用。您可以将listdictionary理解为可变数据结构,其中可以轻松添加新值,并且可以通过索引或按键访问。如果您想在函数内部进行,最好将其重命名,并将字典starthours添加为参数。

def edit_workdaystart(dayoftheweek, starthours):
    ... the same
    ...
    starthours[dayoftheweek] = starthour
    # return starthour  # can be omitted

starthours = {}
for day in daysofweek:
    edit_workdaystart(day, starthours)