BigSteve/Python/030_uselibrary.py
2024-06-03 13:58:34 -04:00

40 lines
1.3 KiB
Python

# Basic example of importing a library/module/class
# 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()