diff --git a/Python/030_uselibrary.py b/Python/030_uselibrary.py new file mode 100644 index 0000000..6cfcc35 --- /dev/null +++ b/Python/030_uselibrary.py @@ -0,0 +1,40 @@ +# Basic example of using try/except to catch errors + +# import the datetime library +# This imports the "datatime" class from the "datetime" module +# (yes, sometimes this is confusing and we just have to accept that) +# (in the immortal words of Noel Cox: Naming things is hard) +from datetime import datetime + +# Get the user's age. +# We loop forever until we get a valid age. +age = -1 +while age < 0: + try: + # Get the age + age = int(input("How old are you?: ")) + # If the age is less than zero, display an error + if age < 0: + print() + print("Error! Valid ages are greater than or equal to zero!") + print() + except: + # If the integer conversion fails (i.e. a non-number was entered) show error + print() + print("Error! You must only enter a whole number!") + print() + +# Print a blank line +print() + +# Calculate the birth year +# using the datetime class method "now()" we get the "year" attribute +current_year = datetime.now().year +# Subtract the current age from current year to get birth year +birth_year = current_year - age + +# Show the user what they typed +print(f"You are {age} years old!") +print(f"You were born in {birth_year}.") +print(" (If this is off by one, why might that be?)") +print() \ No newline at end of file