计算leap年

时间:2018-09-12 02:06:11

标签: python

我有一个作业,应该计算用户输入的年份是否实际上是a年。我不能弄清楚这个公式。有人可以帮忙吗?我可以弄清楚其余的代码,但这是需要的:

2月通常为28天。但如果是a年,则2月为29天。 编写一个程序,要求用户输入年份。然后,程序应显示 该年2月的天数。使用以下条件来确定leap年: 1.确定年份是否可以被100整除。如果是,则当且仅当是is年 如果它也可以被400整除。例如,2000是a年,但2100不是。 2.如果年份不能被100整除,则当且仅当它可以被4整除时,它才是a年。 例如,2008年是a年,但2009年不是a年。

2 个答案:

答案 0 :(得分:1)

from calendar import isleap
year=input('Year: ')
if isleap(int(year)):
   print(29)
else:
   print(28)

或不导入:

year=input('Year: ')
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print(29)
else:
    print(28)

答案 1 :(得分:0)

  

2月通常为28天。但如果是a年,则2月为29天。编写一个程序,要求用户输入年份。然后,程序应显示当年2月的天数。使用以下条件来确定leap年...

作业包含散文中的逻辑/步骤;在注释中编写步骤,然后将注释转换为代码。

我已经完成了下面的第一部分,包括相关的“注释说明”。现在,在每个注释下方编写代码。除其他外,代码应包含if/then/else并使用%(模)运算符。

# 1. Determine whether the year is divisible by 100.
# If it is, then it is a leap year if and only if it is also divisible by 400 [otherwise it is not a leap year]

# 2. [otherwise, ] If the year is not divisible by 100,
# then it is a leap year if and only if it is divisible by 4 [otherwise it is not a leap year]

要构建代码清洁器,请考虑将注释/逻辑放在函数内:

def is_leapyear (year):
    # comments and logic here
    # and 'return' true or false

# call is_leapyear in main program, supplying the year to test

编码需要很多 练习。.所以请练习:)