Created for
>>> user_number = int(input("Enter a number: "))
Enter a number: ada
# ValueError: invalid literal for int() with base 10: 'ada'
print(i)
#NameError: name 'i' is not defined
>>> colors = ["red", "green","blue"]
>>> print( colors[3] )
# IndexError: list index out of range
try:
# code, which can raise an exception
except ExceptionType as e:
# do something if an ExceptionType was raised
else:
# do something if there was no Exception
finally:
# do something no matter if an Exception was raised or not.
# (useful for closing DB connections, etc.)
try
code. ExceptionType is any of the built-in Exception Classes or a User-defined Exception Class.You may have more than one except clauses for different Exception Typestry
clause did not raise any exception.
try:
# code, which can raise an exception
user_number = int(input("Enter a number: "))
except Exception as e:
# do something if an Exception was raised
print("You did not enter a number!")
else:
# do something if there was no Exception
print("Your number is ", user_number)
finally:
# do something no matter if an Exception was raised or not
print("That was all!")
try:
# code, which can raise an exception
except ExceptionType:
# do something only if an ExceptionType was raised
try:
user_number = int(input("Enter a number: "))
except ValueError:
print("You did not enter a number!")
try:
# code, which can raise an exception
except ExceptionType1:
# do something only if an ExceptionType1 was raised
except ExceptionType2:
# do something only if an ExceptionType2 was raised
try:
user_number = int(input("Enter a number: "))
res = 10/user_number
except ValueError:
print("You did not enter a number!")
except ZeroDivisionError:
print("Enter a number different from zero (0)!")
try:
# code, which can raise an exception
except:
# do something if any exception was raised
except
clause
x = 5
y = 0
try:
res = x/y
except:
print("Oops! Something went wrong!")
# Oops! Something went wrong!
def get_user_number():
user_number = int(input("Enter a number: "))
# we forgot to return user_number, thus None is returned
try:
x = get_user_number()
res = 10/x
print("Result is {}".format(res))
except ValueError:
print("You did not enter a number!")
except ZeroDivisionError:
print("Enter a number different from zero (0)!")
except:
print("Oops! Something went wrong!")
Everything looks perfect? Try to enter a CTRL+D : )
def get_user_number():
user_number = int(input("Enter a number: "))
return user_number
try:
x = get_user_number()
res = 10/x
print("Result is {}".format(res))
except ValueError:
print("You did not enter a number!")
except ZeroDivisionError:
print("Enter a number different from zero (0)!")
except:
print("Oops! Something went wrong!")
rasie
statement allows us, to handle the exception, and to raise it after.
try:
user_number = int(input("Enter a number: "))
except ValueError:
print("~"*30)
print("You did not enter a number!")
print("~"*30)
raise
raise
statementraise
statement allows the programmer to force a specified exception to occur.raise
an ExceptionType to be raised
raise
raise
ExceptionType - example
user_name = input("Enter your name: ")
if user_name == "pesho":
raise KeyboardInterrupt
surely, you do not want to do that - it's just an example!
get_string_from_user()
which will get any user input and returns it as string.
def get_string_from_user(msg):
"""
Summary:
Asks the user to enter a string and
- if any error occurs => print:
"***Oops, something went wrong! Try again!" and ask again
Returns the user input, as string, when no errors occurred.
Usage:
user_input = get_string_from_user("enter a user name: ")
Arguments:
msg {[string]} -- [the string to be displayed to the user,]
Returns:
[string] -- [the string entered from user]
"""
def get_string_from_user(msg):
# your definition here
user_name = get_string_from_user("Enter your name, please: ")
user_place = get_string_from_user("Where are you from?: ")
print("Hello {}! How is the weather in {} today?".format(user_name, user_place))
$ python3.6 get_string_from_user.py
Enter your name, please: ^C
***Oops, something went wrong! Try again!
Enter your name, please: iva
Where are you from?: Sofia, Bulgaria
Hello iva! How is the weather in Sofia, Bulgaria today?
get_float_from_user()
which will get from the user a valid python number data-type and will returns it as float.
def get_float_from_user(msg):
"""
Summary:
Asks the user to enter a number and
- if he/she entered no valid python's number value => print:
"***Enter an number, please!" and ask again.
- if any other error occurs => print:
"***Oops, something went wrong! Try again!" and ask again
Returns the user input, as float, when no errors occurred.
Usage:
user_number = get_float_from_user("the message to show to the user")
Arguments:
msg {[string]} - - [the message to show to the user]
Returns:
[float] - - [the number entered from user, converted to float]
"""
def get_float_from_user(msg):
# your definition here
user_height = get_float_from_user("I need to know your height in centimetres: ")
user_weight = get_float_from_user("And your weight in kilograms: ")
print("Your height is: {:5.2f}cm. and you weight {:.2f}kg.".format(user_height, user_weight))
$ python3.6 get_float_from_user.py
I need to know your height in centimetres: pesho
***Enter a number, please!
I need to know your height in centimetres: ^C
***Oops, something went wrong! Try again!
I need to know your height in centimetres: 195
And your weight in kilograms: 98.64
Your height is: 195.00cm. and you weight 98.64kg.
get_string_from_user()
and get_float_from_user()
to improve the user experience in the BMI calculation program, as given in Function - Exercises theme.These slides are based on
customised version of
framework