Reputation: 13
I'm trying to write a program for my Zybooks python course but I do not know how I can get this to work. The prompt is this:
A year in the modern Gregorian Calendar consists of 365 days. In reality, the earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An extra day, February 29th. The requirements for a given year to be a leap year are:
The year must be divisible by 4
If the year is a century year (1700, 1800, etc.), the year must be evenly divisible by 400; therefore, both 1700 and 1800 are not leap years
Some example leap years are 1600, 1712, and 2016.
Write a program that takes in a year and determines whether that year is a leap year.
I tried doing it multiple ways but I don't know what I can do. I want to make it so that numbers divisible by 100 follow the first part of my code and the rest of the numbers that do not meet the criteria follow the second part. Is there any way for me to do this.
First I tried doing:
is_leap_year = False
input_year = int(input())
if input_year % 100 == 0 and input_year % 400 == 0 or input_year % 4 == 0:
print(input_year,'- leap year')
else:
print(input_year,'- not a leap year')
in order to make input_years divisible by 100 and input_years that divide into 400 with no remainder a leap year or if that did not work then for input_years divisible by 4 with no remainder to be counted as leap years; however, this would end with the year 1900 being counted as a leap year when it isn't
(correct) Input 1954 Your output 1954 - not a leap year
(correct) Input 2016 Your output 2016 - leap year
(correct) Input 1600 Your output 1600 - leap year
(Incorrect) Output differs. Input 1900 Your output 1900 - leap year Expected output 1900 - not a leap year
I then tried:
is_leap_year = False
input_year = int(input())
if input_year / 100 and input_year % 400 == 0:
print(input_year,'- leap year')
else:
print(input_year,'- not a leap year')
if input_year % 4 == 0:
print(input_year,'- leap year')
else:
print(input_year,'- not a leap year')
However, this would end in me getting the two outputs seen below:
1900 - not a leap year 1900 - leap year
I also tried switching or with and, but this would mark 2016 as a non-leap year since it would not meet both criterias. Is there any way I can write this so that numbers that divide into 100 only run through the first part of the code and don't try to do go through the second?
Upvotes: 0
Views: 57
Reputation: 443
The problem is that when you check for divisible by 4 you don't force it not to be a century year. Century year is checked for separately.
Use this code:
is_leap_year = False
input_year = int(input())
if input_year / 100 and input_year % 400 == 0:
print(input_year,'- leap year')
elif input_year % 4 == 0 and input_year % 100 !=0 :
print(input_year,'- leap year')
else:
print(input_year,'- not a leap year')
Upvotes: 1