0

How do you best re-write this code in order to have the same output? Possibly with one or more nested loops.

months =["January","February","March","April"]
days_in_month =[32,29,32,31]

jan = months[0]
feb = months[1]
mar = months[2]
apr = months[3]

days_in_jan = days_in_month[0]
days_in_feb = days_in_month[1]
days_in_mar = days_in_month[2]
days_in_apr = days_in_month[3]

for day in range(1,days_in_jan):
    print(jan,day)
for day in range(1,days_in_feb):
    print(feb,day)      
for day in range(1,days_in_mar):
    print(mar,day)
for day in range(1,days_in_apr):
    print(apr,day)

2 Answers 2

1

You can use two loops with enumerate (doc) :

months = ["January", "February", "March", "April"]
days_in_month = [32, 29, 32, 31]

for number_month, month in enumerate(months):
    for one_day in range(1, days_in_month[number_month]):
      print(month, one_day)

Another method, if the two lists are of the same length:

months = ["January", "February", "March", "April"]
days_in_month = [32, 29, 32, 31]

for i in range(len(months)):
    for one_day in range(1, days_in_month[i]):
      print(months[i], one_day)
Sign up to request clarification or add additional context in comments.

Comments

0

First, you could convert months and days into a dictionary key-value pair:

months = ["January","February","March","April"]
days_in_months = [32,29,32,31]
month_dict = dict(zip(months,days_in_months))

Then, you can get the same result with a nested for loop:

for month in month_dict: 
    for day in range(1,month_dict[month]): 
        print(month,day)

1 Comment

make sure you close the post by marking the best answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.