Write a program that determines whether a year is a leap year. Prompt the user to enter a year and output whether it is a leap year.
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("The year", year, "is a leap year")
else:
print("The year "+str(year)+" is not a leap year") # another way to format a message with variables
These test cases have been created with AI, cross check anything important.
2024
The year 2024 is a leap year
2023
The year 2023 is not a leap year
1900
The year 1900 is not a leap year
2000
The year 2000 is a leap year
This explanation has been created with AI, cross check anything important.
The program starts by asking the user to enter a year. The input()
function reads the year as text, and int()
converts it to a whole number.
year = int(input("Enter a year: "))
The code then checks if the entered year is a leap year using an if
statement. A year is a leap year if it's divisible by 4 but not divisible by 100, OR if it's divisible by 400.
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
year % 4 == 0
checks if the year is divisible by 4 (remainder is 0). year % 100 != 0
checks if the year is NOT divisible by 100. year % 400 == 0
checks if the year is divisible by 400.
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0
If the condition in the if
statement is true (the year is a leap year), the program prints a message saying that the year is a leap year. It uses commas to separate the different parts of the output string.
print("The year", year, "is a leap year")
If the condition in the if
statement is false (the year is not a leap year), the program executes the else
block and prints a message saying that the year is not a leap year. Here the code constructs a string to print using +
for concatenation and str()
to convert the integer year to a string.
else:
print("The year "+str(year)+" is not a leap year")
These exercises have been created with AI, cross check anything important.
similar
Write a program that asks the user for a number and prints whether it is even or odd.moderate
Write a program that takes three numbers as input and prints the largest of the three.challenge
Write a program that determines if a given date (day, month, year) is valid. Consider leap years when validating the date. The program should output “Valid Date” or “Invalid Date.”challenge
Write a program that takes a year as input and determines the day of the week for January 1st of that year. (Hint: You might need to research Zeller's Congruence or another algorithm for determining the day of the week.)