[英]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("")
好的,我如何循环播放,而不是1、2、3月的一月,二月等。
尝试这样的事情:
import datetime
months = [datetime.date(2000, m, 1).strftime('%B') for m in range(1, 13)]
for month in months:
print month
另外,这样的方法也可以:
import calendar
for i in range(1, 13):
print calendar.month_name[i]
尝试这个:
# fill a tuple with the month's names
for y in ('January', 'February', etc):
# do something
或者,创建一个元组,其索引将月份的数字映射到名称,从索引1
开始(我将第一个位置填充为None
因为将不使用索引0
):
months = (None, 'January', 'February', etc)
for y in range(1, 13):
m = months[y] # `m` holds the month's name
注意,我使用的是元组而不是列表,因为月份名称不太可能更改。 而且,尽管我们可以使用将月份数字映射到名称的dict
,但是对于这种简单情况而言,这是过分的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.