在Python中嵌套while和for循环

时间:2015-10-06 11:06:17

标签: 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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以在年度循环的每次迭代中嵌入内部月循环,如下所示。这将询问一年的年份数,然后是每个月读数的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)