简体   繁体   中英

Nested while and for loops in Python

I want to write a program that asks the user for number of years and then the temperature for each month for as many number of years as they have decided in the input like this:

Which is the first year?: 2015

Month 1: 25 

Month 2: 35 
.
.
.

for 12 months and I have written a code that works for that:

This is the outer loop for years:

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

This is the inner loop for months:

monthnumber = 1

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

My question is, where do I place the inner loop for months so that the code continues like this:

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:

I have tried putting it in different places but without success.

There is no need for while loop two for loop is enough

Code:

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) + ": ")

Edited Code:

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

You can embed your inner month loop inside each iteration of the year loop, like below. This will ask for the year number once, followed by 12 questions for each months reading, followed by the next iteration.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM