More basics
This commit is contained in:
parent
58b19d3111
commit
8935995ce5
40
Python/030_uselibrary.py
Normal file
40
Python/030_uselibrary.py
Normal file
|
@ -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()
|
Loading…
Reference in New Issue
Block a user