-2

我很难对代码进行故障排除。我要做的就是让用户输入开始和结束的年份,然后能够计算其间的所有闰年。我对 Python 还是很陌生,只是无法弄清楚为什么我的 while 循环没有做我想做的事情。

starting = int(raw_input('Enter starting year: '))
ending = int(raw_input('Enter ending year: '))
print 'Leap years between', starting, 'and', ending
while starting <= ending:
    if starting % 4 == 0 and starting % 100 != 0:
       print starting
    if starting % 100 == 0 and starting % 400 == 0:
       print starting
    starting = starting + 1

这就是我现在所拥有的。我真的不想得到刚刚给我的答案,但如果我能得到一点提示,说明为什么我的 while 循环不起作用,我会非常感激。

这是我在 IDE 中看到的输出:

ide截图

4

3 回答 3

2

代码工作得很好。这是以下会议:

Enter starting year: 2008
Enter ending year: 2032
Leap years between 2008 and 2032
2008
2012
2016
2020
2024
2028
2032

这与给她的信息完全吻合。

控制台会话:

>>> from leapyear import leap
>>> leap()
Enter starting year: >? 2008
Enter ending year: >? 2032
Leap years between 2008 and 2032
2008
2012
2016
2020
2024
2028
2032

闰年.py

def leap():
    starting = int(raw_input('Enter starting year: '))
    ending = int(raw_input('Enter ending year: '))

    print 'Leap years between', starting, 'and', ending
    while starting <= ending:
        if starting % 4 == 0 and starting % 100 != 0:
            print(starting)
        if starting % 100 == 0 and starting % 400 == 0:
            print(starting)
        starting += 1

您还可以使用列表推导来执行此功能:

def new_leap(start, end):
    return [x for x in xrange(start, end + 1)
            if (x % 400 == 0) or (x % 4 == 0 and not x % 100 == 0)]

控制台会话:

>>> from leapyear import new_leap
>>> new_leap(2008, 2032)
[2008, 2012, 2016, 2020, 2024, 2028, 2032]
于 2013-09-23T04:19:03.603 回答
0
def is_leap(year):
    leap = False

    if year%4 ==0 :
        leap = True

    elif year%100 ==0:
        leap = False

    elif year%400 ==0:
        leap = True

    return leap


year = int(raw_input())
print is_leap(year)
于 2020-01-14T09:21:27.587 回答
0

我认为这将包含所有测试用例

我们在 value=c 中添加了所有无效的情况,并从 b 中匹配并删除了该值

def is_leap(year):
    leap = False
    leap1=True
    b=[]
    for a in range(1800,year+200,4):
        b.append(a)
    c=[1800,1900,2100,2200,2300,2500,2600,2700,2800,2900]
    for d in range(len(c)):
        e=c[d]
        if e in b:
            b.remove(e)
    if year in b:
        return leap1
    else:
        return leap
year = int(input())
print(is_leap(year))
于 2019-02-27T08:49:36.017 回答