2015-10-06 46 views
0

循環我想編寫一個程序,要求用戶的年數,然後將溫度每個月多達數年,他們在這樣的輸入決定:嵌套while和for在Python

Which is the first year?: 2015 

Month 1: 25 

Month 2: 35 
. 
. 
. 

12個月,我已經寫了一個可行的代碼:

這是多年來外環:

loops = int(input("How many years?: ")) 
count = 1 

while count < loops: 
    for i in range (0,loops): 
    input("Which is the " + str(count) + ": year?: ") 
    count += 1 

這是個內部循環:

monthnumber = 1 

for i in range(0,12): 
     input("Month " + str(monthnumber) + ": ") 
     monthnumber += 1 

我的問題是,我在哪裏放置內環數月,這樣的代碼將繼續這樣的:

Which is the 1 year? (input e.g. 2015) 

Month 1: (e.g. 25) 

Month 2: (e.g. 35) 
..... for all twelve months and then continue like this 

Which is the 2 year? (e.g. 2016) 

Month 1: 

Month 2: 

我試圖把它在不同的地方,但沒有成功。

回答

2

沒有必要while循環two for loop is enough

代碼:

loops = int(input("How many years?: ")) 
for i in range (1,loops+1): 
    save_to_variable=input("Which is the " + str(i) + ": year?: ") 
    for j in range(1,13): 
     save_to_another_variable=input("Month " + str(j) + ": ") 

編輯代碼:

loops = int(input("How many years?: ")) 
count = 1 
while count < loops:    
    save_to_variable=input("Which is the " + str(count) + ": year?: ") 
    for j in range(1,13): 
     save_to_another_variable=input("Month " + str(j) + ": ") 
    count+=1 
+0

謝謝,但任務是使用一個while循環與它內部的for循環,嵌套。任何想法如何使用我有的代碼,但只放置內循環,以便它是正確的? –

+0

@ J.Se如果你真的需要使用它,那麼只需在while循環的第一個循環上添加while循環 – The6thSense

+0

@vigneskalai你能告訴我你的意思嗎? –

1

您可以嵌入裏面每個內每月循環迭代的一年l像下面一樣。這將要求一年的數字,然後是每個月讀數的12個問題,然後是下一次迭代。

from collections import defaultdict 
loops = int(input("How many years?: ")) 
temperature_data = defaultdict(list) 
for i in range(loops): 
    year = input("Which is the " + str(i) + ": year?: ") 
    for m in range(12): 
     temperature_reading = input("Month " + str(m) + ": ") 
     temperature_data[year].append(temperature_reading) 
+0

感謝您的回覆,但是沒有任何方法可以保持我所做的一切,並將內部循環放在某處以實現相同的結果?它必須是一個具有for循環的while循環。 –