37 lines
1.4 KiB
Python
37 lines
1.4 KiB
Python
# Basic example of using try/except to catch errors
|
|
|
|
# Get the user's age. The input function always returns
|
|
# a string. In order to do math operations on user input
|
|
# we have to convert it to an number/integer. However, any user
|
|
# input that is NOT a number (integer in this case) will cause
|
|
# a fatal error and the program will crash. We use a try/except
|
|
# to catch this event and keep requesting input until the value
|
|
# is a valid integer.
|
|
# We loop forever asking for a valid age. The initial unacceptable
|
|
# value for age means the loop will be executed at least once.
|
|
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()
|
|
|
|
# Show the user what they typed
|
|
# the "f" before the quote means that this string is "formatted"
|
|
# Formatted strings can use curly bracket notation to embed
|
|
# variables inside a string. This is handy as it handles variable
|
|
# type conversion automatically (i.e. integer to string)
|
|
print(f"You are {age} years old!")
|
|
print() |