'Calculating the next leap year from input in python
In my course, I'm supposed to write a program which takes input as a year and return its following leap year. I already wrote the condition if user input is already a leap year, but I'm unable to write logic if the user input is not a leap year.
Thankful for any tips!
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?
Solution 1:[1]
you can do this using while loop like this
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}")
Solution 2:[2]
Unfortunately, python does not have a do while
option, but you can use a while
loop like this:
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}")
Solution 3:[3]
You can create a function:
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))
Solution 4:[4]
I have tried the 3 solutions here but they don't work with century year. for example the next leap year following 1896, should be 1904 and not 1900 since 1900 is not dividable by 400. This code was tested and accepted for the exercise "The next Leap year" in part 2 of Python programming MOOC 2021 by the University of Helsinki where you can find also the official model solution.
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}")
Solution 5:[5]
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}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aakash Dinkar |
Solution 2 | |
Solution 3 | |
Solution 4 | Nzayem jihed |
Solution 5 | user18837188 |