2015-10-06 27 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循环。 –