0

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but the task is using a while loop with a for loop inside it, nested. Any idea of how I can use the code I have, but only place the inner for loop so that it is correct?
@J.Se IF you really need to do it using while then place just add the while loop above first for loop
@vigneskalai could you please show me how you mean?
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)

1 Comment

Thanks for replying, but isn't there any way just to keep everything the way I have done it and put the inner loop somewhere to achieve the same result? It has to be a while loop with a for loop inside it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.