Reputation: 1
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)
Upvotes: 0
Views: 565
Reputation: 31
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)
Upvotes: 1
Reputation: 97
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)
Upvotes: 0