Advertisement
acclivity

pySimpleLeapYearTest

Sep 5th, 2022 (edited)
964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. # Simple Python script to accept a year from user input, check it is within a certain range,
  2. # and check if it is a leap year
  3.  
  4. def isleap(yr):
  5.     # This function receives an integer year in "yr" (which has already been tested for valid range)
  6.     # It returns True if the year is a leap year
  7.     # It returns False if the year is not a leap year
  8.     # The function will produce valid result for all years 1901 to 2099 inclusive
  9.     # For this range of years, all years that are exactly divisible by 4 are leap years
  10.     if yr % 4:
  11.         return False        # The division did NOT result in zero, therefore yr is not leap
  12.  
  13.     return True             # yr is leap
  14.  
  15.  
  16. # Here I have written code that will loop indefinitely
  17. while True:
  18.  
  19.     # input() always gives us a string
  20.     uyear = input("Enter a year from 1901 to 2099 inclusive: ")
  21.  
  22.     # Here we test if the string uyear contains digits only
  23.     if uyear.isdigit():
  24.  
  25.         # Yes, uyear is numeric. We can convert it to an integer
  26.         year = int(uyear)           # now year is an integer
  27.  
  28.         # Here we test if the year is greater than 1900 and less than 2100
  29.         # (it is important not to allow 1900 or 2100, as those years break the simple divisable by 4 rule)
  30.         if 1900 < year < 2100:
  31.             # Yes the year is valid (within the range we are interested in)
  32.             # Call our function that tests if the year is a leap year or not
  33.             if isleap(year):
  34.                 # The function returned "True" therefore the year is a leap year
  35.                 print(f"Year {year} is a leap year")
  36.             else:
  37.                 # the function returned False, therefore the year is not a leap year
  38.                 print(f"Year {year} is not a leap year")
  39.  
  40.             # Here we say "continue" to go around the While True loop again, without printing "invalid"
  41.             continue
  42.  
  43.     # Either the user input was not numeric, OR the year was out of range
  44.     print("Invalid year")
  45.  
  46.     # Now the code will go around the "while True" loop again
  47.  
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement