按统一顺序打印出日期和计数器

时间:2016-09-23 18:21:49

标签: python

我这几个小时都在做这些!请帮忙!新的python

1990年的输入年份 和2000年结束。

基本上我希望输出为

  

这些年是1992年的1996年2000年

     

有3个计数

我想将它们转换为列表并使用len(),但我不知道如何

#inputs
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))

print "The number of leap years are "

counter = 0
for x in range(year,endyear+1):

    if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
        counter +=1
        print x
        print counter
  

继承人当前的结果:(

闰年数

1900
0
1901
0
1902
0
1903
0

3 个答案:

答案 0 :(得分:1)

问题是当需要年份时,break停止了你的循环。

year = int(raw_input("Input year: "))
end_year = int(raw_input("Input end year:"))

print "The number of leap years are "

counter = 0
temp = []
for x in range(year, end_year+1):
    if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
           counter +=1
           temp.append(x)
print('the years are {}'.format(temp))
print('there are {} counts'.format(counter))

您可能还想删除“年份为[]”中的括号,您可以使用

执行此操作
print('the years are ', ' '.join(map(str, temp)))

答案 1 :(得分:1)

您可以使用calendar.isleap计算给定年份之间的闰年数。

from calendar import isleap
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
years = []
for x in range(year,endyear+1):
    if isleap(x):
        counter +=1
        print x
        print counter

答案 2 :(得分:0)

你可以用更短的方式做到:

from calendar import isleap
years = [ str(x) for x in range(year,endyear+1) if isleap(x)]

print "the years are ", ''.join(elem + " " for elem in years)
print "there are ", len(years), "counts"