在python中根据输入计算下一个闰年

4uqofj5v  于 2023-02-07  发布在  Python
关注(0)|答案(7)|浏览(156)

在我的课程中,我应该编写一个程序,它将输入作为年份并返回下一个闰年,我已经编写了用户输入已经是闰年的条件,但如果用户输入不是闰年,我就无法编写逻辑。
感谢所有的提示!

year = int(input("Give year:"))
leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0

if leap:
    print(f"The next leap year from {year} is {year + 4}")
# what next?
70gysomp

70gysomp1#

你可以像这样使用while循环

inp_year = int(input("Give year:"))
year = inp_year
leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0

if leap:
   print(f"The next leap year from {year} is {year + 4}")

while not leap:
    year += 1
    leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0
print(f"The next leap year from {inp_year} is {year}")
11dmarpk

11dmarpk2#

不幸的是,python没有do while选项,但是你可以像这样使用while循环:

year = int(input("Give year:"))
original = year
leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0

while not leap:
    year += 1
    leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0

print(f"The next leap year from {original} is {year}")
up9lanfz

up9lanfz3#

您可以创建函数:

def find_leap(year, first):
    if not first and ((year % 4 == 0 and year % 100 != 0) or (year % 100 == 0 and year % 400 == 0)):
        return year
    else:
        return find_leap(year+1, False)

year = int(input("Give year: "))
print("The next leap year from", year, "is", find_leap(year, True))
xytpbqjk

xytpbqjk4#

我试过这里的3个解决方案,但他们不工作的世纪年。例如,下一个闰年以下1896年,应为1904而不是1900,因为1900不能被400整除。此代码已在“下一个闰年”练习中测试并接受在赫尔辛基大学的Python编程MOOC 2021的第2部分中,您也可以找到官方模型解决方案。

year = int(input("Year: "))

initial = year

while True:

    year += 1

    if year % 4 == 0 and (year % 100 != 0 and year % 400 != 0):
        break

    elif year % 100 == 0 and year % 400 == 0:
        break

print(f"The next leap year after {initial} is {year}")
q9yhzks0

q9yhzks05#

yr = int(input("Year: "))
new = yr

while True:
    new += 1
    if (new % 4 == 0 and new % 100 != 0) or new % 400 == 0:
        break
print(f"The next leap year after {yr} is {new}")
kmynzznz

kmynzznz6#

使用嵌套条件:

year = int(input("Year: "))
leap = year

while True:
    leap += 1
    if leap % 100 == 0:
        if leap % 400 == 0:
            break
    elif leap % 4 == 0:  
        break
        
print(f"The next leap year after {year} is {leap}")
zysjyyx4

zysjyyx47#

这是2023年课程的示范解决方案。

start_year = int(input("Year: "))

year = start_year + 1

while True:

    if year % 100 == 0:
        if year % 400 == 0:
            break
    elif year % 4 == 0:
        break
 
    year += 1
 
print(f"The next leap year after {start_year} is {year}")

相关问题