Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Simple Python script to accept a year from user input, check it is within a certain range,
- # and check if it is a leap year
- def isleap(yr):
- # This function receives an integer year in "yr" (which has already been tested for valid range)
- # It returns True if the year is a leap year
- # It returns False if the year is not a leap year
- # The function will produce valid result for all years 1901 to 2099 inclusive
- # For this range of years, all years that are exactly divisible by 4 are leap years
- if yr % 4:
- return False # The division did NOT result in zero, therefore yr is not leap
- return True # yr is leap
- # Here I have written code that will loop indefinitely
- while True:
- # input() always gives us a string
- uyear = input("Enter a year from 1901 to 2099 inclusive: ")
- # Here we test if the string uyear contains digits only
- if uyear.isdigit():
- # Yes, uyear is numeric. We can convert it to an integer
- year = int(uyear) # now year is an integer
- # Here we test if the year is greater than 1900 and less than 2100
- # (it is important not to allow 1900 or 2100, as those years break the simple divisable by 4 rule)
- if 1900 < year < 2100:
- # Yes the year is valid (within the range we are interested in)
- # Call our function that tests if the year is a leap year or not
- if isleap(year):
- # The function returned "True" therefore the year is a leap year
- print(f"Year {year} is a leap year")
- else:
- # the function returned False, therefore the year is not a leap year
- print(f"Year {year} is not a leap year")
- # Here we say "continue" to go around the While True loop again, without printing "invalid"
- continue
- # Either the user input was not numeric, OR the year was out of range
- print("Invalid year")
- # Now the code will go around the "while True" loop again
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement