0

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.")
  • 1
    Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Apr 21 '23 at 22:55
  • 1
    That's a question of opinion. My solution is one line of code after the input: `print(('Not leap year', 'Leap year.')[bool((not year % 4) and (year % 100) or (not year % 400))])`. Is this better? Who can say? – Matthias Apr 21 '23 at 23:02
  • The second `elif` in your code should be a simple `else`. – Matthias Apr 21 '23 at 23:05

1 Answers1

0

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.

  • Ok thanks for pointing that out. I want to mske sure Im not developing bad habits. – NolongerHuman Apr 21 '23 at 23:14
  • @NolongerHuman A bad habit is mixing logic and input/output. You should have a function `is_leap_year` with the year as a parameter and a boolean return value. This function determines if a year is a leap year, it doesn't do any printing. Then call this function and print the appropriate message based on the return value. – Matthias Apr 21 '23 at 23:19