In this post, we will find out whether the given year is a leap or not in Python using a while loop.
A leap year is a year divisible by 4, except for century years (years ending with 00), which must be divisible by 400 to be a leap year.
Here is a program in Python to check if a given year is a leap year or not using a while loop.
Simple Code:
year = int(input("Enter year: "))
leap = False
while True:
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
leap = True
else:
leap = False
else:
leap = True
else:
leap = False
break
if leap:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Output:
Enter year: 2006
2006 is not a leap year.
Enter year: 2000
2000 is a leap year.
Explanation with comments:
# Taking input from user
year = int(input("Enter year: "))
# Initializing variables
leap = False
# Checking if year is a leap year
while True:
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
leap = True
else:
leap = False
else:
leap = True
else:
leap = False
break
# Printing the result
if leap:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Explanation:
The program takes the year as input from the user and initializes a boolean variable ‘leap’ to False.
It then uses a while loop to check if the year is a leap year by checking if it is divisible by 4, 100, and 400.
If it is, it sets ‘leap’ to True, otherwise, it sets it to False. Finally, it prints the result.
Note: The program can be optimized further by removing the while loop and using if-else statements.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.