user3373402
user3373402

Reputation: 53

How do I loop over the months of the year and print them in python?

year = int(input("Enter number of years: "))
total = 0

for x in range(year):
for y in range(1,13):
    print("Year {0}".format(x+1))
    precipitation = int(input("Enter precipitation for month {0} mm: ".format(y)))

    total = total + precipitation


totalmonths = year * 12
average = total/totalmonths
print("")

Ok how do i loop it so instead of month 1 , 2 ,3 its January , February etc.

Upvotes: 2

Views: 11836

Answers (2)

Tim S
Tim S

Reputation: 5101

Try something like this:

import datetime

months = [datetime.date(2000, m, 1).strftime('%B') for m in range(1, 13)]
for month in months:
  print month

Alternatively, something like this would also work:

import calendar

for i in range(1, 13):
  print calendar.month_name[i]

Upvotes: 8

Óscar López
Óscar López

Reputation: 236034

Try this:

# fill a tuple with the month's names
for y in ('January', 'February', etc):
    # do something

Alternatively, create a tuple whose indexes map months' numbers to names, starting at index 1 (I'm filling the first position with None because the index 0 won't be used):

months = (None, 'January', 'February', etc)
for y in range(1, 13):
    m = months[y] # `m` holds the month's name

Notice that I'm using tuples and not lists because month names are unlikely to change. And although we could use a dict that maps month numbers to names, that would be overkill for this simple case.

Upvotes: 1

Related Questions