2017-10-26 6 views
0

私はそれを呼び出すたびに関数からの戻り値のすべてを格納する方法はありますか?関数内で新しい変数を自動的に生成するにはどうすればよいですか?

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) 

あなたはそれが機能して、リスト内の項目を実行しますが、私はその日の開始時間は、目的球の外で変数として格納したい見ることができるように:ここではコードです。

+1

これは 'x = workdaystart(day)'のように、開始時刻を変数 'x'に格納します。 – Barmar

+0

しかし、それはオーバーライドされ続けるでしょう。ループの後、 'x'の値は日曜日の値になります。日付をキーに、開始時間を値として辞書を作成する – ton

答えて

1

あなたが時間を開始する曜日名をマッピングした辞書を探しているように聞こえる:

starthours = {} 
for day in daysofweek: 
    starthours[day] = workdaystart(day) 
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) 
0

あなたは返さstarthour値のリストを生成できます。

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

Barmarの答えは非常に便利です。 listまたはdictionaryは、新しい値を簡単に追加でき、インデックスまたはキーでアクセスできる、変更可能なデータ構造として理解できます。関数内で実行したい場合は、名前を明確に変更し、辞書として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) 
関連する問題