I had a small project, I am a beginner with python in the 100 days of code with Dr.Angela Yu and was tasked to write code for a leap year checker. I wrote the code different from her and wanted to know was this ok to do since it ended up working still or was the way she wrote it considered cleaner and a more appropriate way to have written the code?
#This is my code:
year = int(input("Which year do you want to check? "))
if year % 4 == 0 and year % 100 != 0 and year % 400 != 0:
print("Leap year.")
elif year % 4 != 0:
print("Not leap year.")
elif year % 4 == 0 and year % 100 == 0 and year % 400 != 0:
print("Not leap year.")
#This was her code:
year = int(input("Which year do you want to check? "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
In your code, you check certain conditions multiple times like the year % 4 == 0 whereas in the class’s code, each case is only checked once. In this short of a program, that is a small difference of the time that it takes, but it is bad practice because over time with a bigger program, that time loss would add up. TLDR It works but is bad practice to check each case more than once if it is not required.