# Noemi Cabrera
# 20 November 2021
# In this lesson, I learned to differentiate between exception types and recognize their meaning,
# how to handle a raised exception by using a try..except statement, how to handle different exception types
# by using the try..except statement with an an additional except statement with no specified error,
# use else and finally to perform clean-up actions (close a file, run specific code, etc.), and raise
# a forced exception of a specific type when needed.
# I had some minor difficulties when writing some of the programs. When writing some of the
# programs requested in the tasks, I got many errorsalong the way because I often forgot to
# convert input or variables to integers to perform operations, or using the wrong syntax in
# the except statements.
# In this code, an error/exception is produced because 'lst' only has indexes 0,1,and 2 and index 30
# is entered as an index of 'lst'. Index out of range error displays
lst = [0, 1, 2]
print(lst[30])
# [ In this code, an error/exception is produced because the variable 'x' is used in a print statement
# without being defined first. A name error is displayed. ]
# x is not defined anywhere
print(x)
# [ In this code, an error/exception is produced the variables s1 and s2, which contain string data, are being
# divided. Because you need date to be integer type to perform division, a TypeError is displayed.
# without being defined first. A name error is displayed. ]
s1 = 'Word1'
s2 = 'Word2'
s1/s2
# In this code, an error/exception is produced because the date module is imported. Since this module is not
# found, a ModuleNotFoundError is displayed. ]
# [ ] Write an expression to raise a `ModuleNotFoundError` exception
import date
c_date = date.today()
print(c_date)
# IN this code, an error/exception is produced because the timdelta function cannot be found in the
# datetime module. An ImportError is displayed
# [ ] Write an expression to raise an `ImportError` exception
from datetime import timdelta
delta_t = timedelta(hour= 6, minute = 56)
# In this code, the division 5/0 is used in a try..except statement to see if it has one errors. If it
# does, then the code below the error will display and the program will keep running. If it doesn't,
# the program will run normaly.
try:
5/0
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Program is still running")
# In this code , the 'lst' list is created containing a string and 2 integers as its items. Then, a for..in loop
# is used to iterate through each item in the list and divide each one by the index count Lastly, a try..except statement is
# used in the loop to check for multiple errors and still execute the code despite any raised errors.
# Since 'lst' had only indexes 0,1,and 2, a index error is produced because the range was until index 4.
# The cell runs despite this.
lst = ['text', 5, 12]
for i in range(5):
try:
print(lst[i] / i)
print("print executed")
except TypeError:
print("Cannot divide strings")
except IndexError:
print("Cannot access out of range elements")
# In this code , the 'x' list is created containing an integer as its item. Then, a try..except statement is
# used to check if there is a ZeroDivision Error when performing the division. Since this only checks for 1 error,
# any other errors encountered make the code display an error and the rest will not execute.
# Without handling unexpected exception
x = [5]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# In this code , the 'x' list is created containing an integer as its item. Then, a try..except statement is
# used to check if there is a ZeroDivision Error when performing the division. In addition, an except statement
# without any specified error is used to handle any other unexpected errors and the code can run normally.
# Handling unexpected exception
x = [5]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except:
print("Unexpected error")
# In this code , the 'old_list' list is created with multiple data types as its items. A list named 'new_list'
# is initialized. A for..in loop is created to iterate through each item in the old_list until it reaches
# index 5. Then, a try..except statement is used inside the loop to check if there is a TypeError, or
# ZeroDivision Error when performing the division of 12 by the list items. In addition, an except statement
# without any specified error is used and stored in the exception_object variable to handle any other
# unexpected errors and the code can run normally. The new_list is printed
# Handling unexpected exception
old_lst = [6, 'word', [2, 5], 0, 3]
new_lst = []
for i in range(6):
try:
tmp = 12 / old_lst[i]
new_lst.append(tmp)
print("List appended with", tmp)
except TypeError:
print("Cannot divide {0:d} by {1:}".format(12, type(old_lst[i])))
except ZeroDivisionError:
print("Cannot divide by 0")
# Handling unexpected exceptions, by showing the associated error message
except Exception as exception_object:
print("Unexpected error: {0:}".format(exception_object))
print()
print("The new list is:", new_lst)
# In this code, the sqrt function is imported from the math module. Then, its used to calculate the
# square root of the value in the x variable. Since the balue is a negative number, this code displays
# a value error and other code cannot be run since this error is not handled.
# Without exception handling
from math import sqrt
x = -3
sqrt(x)
# In this code, the sqrt function is imported from the math module. Then, its used to calculate the
# square root of the value in the x variable inside a try..except statement. If this code produces a
# value error, the error message is stored in te exception_object variable and the code can run because this
# error is handled.
# With exception handling
from math import sqrt
x = -3
try:
sqrt(x)
except ValueError as exception_object: # Storing the error message in exception_object
print(exception_object)
# In this code , the 'lst1' and 'lst2' lists are created with multiple data types as their items.
# A for..in loop is created to iterate through each item in both lists until it reaches
# index 6. Then, a try..except statement is used inside the loop to check if there is a TypeError or
# Index Error when performing the addition of 'lst1' and 'lst2'. In addition, an except statement
# without any specified error is used and stored in the exception_object variable to handle any other
# unexpected errors and the code can run normally. The message "Done" is printed
# [ ] The following program adds `lst1` to `lst2` element by element
# Find all exceptions that will be generated by this program,
# then handle the exceptions by displaying meaningful messages.
# You should also handle unexpected exceptions.
lst1 = [-4, -5, 6, [6], "hello"]
lst2 = [ 5, 16, [6], "hello", "goodbye"]
for i in range(7):
try:
lst1[i] + lst2[i]
except TypeError:
print("Items cannot be added because their data type is different.")
except IndexError:
print("Index is out of range. 'lst1' only has indexes 0-4 ")
except Exception as exception_object:
print("Unexpected error: {0:}".format(exception_object))
print("Done!")
# In this code , the user is asked to enter an integer, whic is stored in the 'x' variable. Then, a
# try..except statement is used to check if there is a Type Error when performing the division of 'x' by 2.
# In addition, an except statement without any specified error is used to handle any other unexpected errors
# and the code can run normally.
# Handling unexpected exception
# [ ] The following program asks the user for an integer then prints the result of dividing it by 2.
# If the user enters an invalid value (i.e. "4.3" or "Hello"), the program terminates.
# Use exception handling to deal with unexpected user input and display a meaningful message.
x = input("Enter an integer: ")
try:
x = int(x)
print("{:d} / 2 = {:.2f}".format(x, x / 2))
except TypeError:
print("Cannot divide {0:d} by {1:}".format(type(x), 2))
except Exception as exception_object:
print("Unexpected error: {0:}".format(exception_object))
print("Done!")
# In this code, the x and y variables are asigned integers as their values. Then, a try..except statement is
# used to check if there is a ZeroDivision Error when performing the division of x divided by y. In addition, an
# else statement is added. In case no errors were raised, the code below the else statement is executed.
x = 3
y = 2
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("All good! No exceptions were raised.")
# In this code , the 'x' and 'y' variables are assigned integers as their values. Then, a try..except statement is
# used to check if there is a ZeroDivision Error when performing the division of x divided by y. In addition, an
# except statement without any specified error is used to handle any other unexpected errors and the code can run normally.
# Lastly, the finally statement is used to run the code below whether an error was raised or not.
# Handling unexpected exception
x = 3
y = 2
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Code that will run whether an exception was raised or not")
# In this code , the 'x' and 'y' variables are assigned integers as their values. Then, a try..except statement is
# used to check if there is a ZeroDivision Error when performing the division of x divided by y. In addition, an
# except statement without any specified error is used to handle any other unexpected errors and the code can run normally.
# Lastly, the finally statement is used to run the code below whether an error was raised or not.
x = 3
y = 0
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Code that will run whether an exception was raised or not")
# In this code, the user is asked to enter an integer, which is stored in the x variable. Then, a try..except
# statement is used to check if there is a ValueError when performing the division of x and 2. A exception statement
# is added to handle any unexpected error. In addition, an else statement is added. In case no errors were raised,
# the code below the else statement is executed.
# [ ] The following program asks the user for an integer `x` then assigns `y` as the result of dividing `x` by 2.
# If the user enters an invalid value (i.e. "4.3" or "Hello"), the program terminates.
# Use exception handling to deal with unexpected user inputs, then use an `else` clause to calculate the value of `y`.
10
x = input("Enter an integer: ")
try:
y = None
x = int(x)
y = x / 2;
except ValueError:
print("y cannot be used if it equals a decimal, letters, or is blank")
except Exception as exception_object:
print("Unexpected error: {0:}".format(exception_object))
else:
print("No exceptions were raised, you can use y =", y)
# In this code, a file is opened in write mode and then closed. The file is opened again in read mode and
# a try..except statement is used to check if there is an unexpected Error when trying to write to the file
# using an except statement without any specified error.
# Lastly, the finally statement is used to close the file whether an error was raised or not.
# [ ] The following program tries to write to a file opened for reading.
# The program will terminate before closing the file, and the file resources will not be released.
# Use exception handling with a `finally` clause to make sure the file is closed.
#create the text file in whatever directory you are in
f = open("text_file.txt", 'w')
f.close()
# Open a text file for reading
# This open will work after the code above opens text_file.txt as 'w'
f = open("text_file.txt", 'r')
# Try to write to a file open for reading (will raise an exception)
try:
f.write("This string will not be written")
except Exception as exception_object:
print("Unexpected error: {0:}".format(exception_object))
finally:
f.close()
print("File closed")
# In this code, the while loop runs while True. The try..except statement is used to check if a
# ValueError is raised and a Value Error is created by using the raise keyword. This value error
# is raised if the values of "x" are less than 1 or greater than 10. While breaks if valid is False.
valid = False
while not valid:
try:
x = int(input("Enter a number between 1 and 10: "))
if ((x < 1) or (x > 10)):
raise ValueError("The number is outside of the acceptable range")
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))
# In this code, the isValid function is defined and if the value of "num" is less than 1 or greater than 10, it
# rises a Value Error. The while loop runs while True. The try..except statement is used to check if a
# ValueError is raised and the is Valid function determines if the number is acceptable. While breaks if valid is False.
def isValid(num):
if ((num < 1) or (num > 10)):
raise ValueError("The number is outside of the acceptable range")
else:
return num
valid = False
while not valid:
try:
x = int(input("Enter a number between 1 and 10: "))
x = isValid(x)
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))
# In this code, the user is asked to enter an odd positive number, which is stored in the num variable
# and is converted to an integer.The while loop runs while True. The try..except statement is used to raise a Value
# Error if number entered by the user is even or negative. While breaks if valid is False.
# The number entered is displayed if valid.
# [ ] Write a program to keep prompting the user for an odd positive number until a valid number is entered.
# Your program should raise an exception with an appropriate message if the input is not valid.
valid = False
while not valid:
try:
num = int(input("Enter an odd positive number:"))
odd_num = num % 2
if ((num < 0) or (odd_num == 0)):
raise ValueError("The number cannot be negative or even.")
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} is valid".format(num))
# In this code, the isValid function is defined and if the value of "num" is less than 0 or has a remainder
# of 0 when you divide it in half, it raises a Value Error. The user is asked to enter an odd positive number,
# which is stored in the 'num' variable and is converted to an integer. The while loop runs while True. The
# isValid function is used in the try..except statement to check of the number of the user is valid.
# While breaks if valid is False. The number entered is displayed if valid.
# [ ] Complete the function `isValid` to test the validity of a user input. A valid input should be an odd positive integer.
# The function should raise an exception with an appropriate message if the input is not valid.
# The function need not handle the exception.
def isValid(num):
#TODO
odd_num = num % 2
if ((num < 0) or (odd_num == 0)):
raise ValueError("The number cannot be negative or even.")
else:
return num
valid = False
while not valid:
try:
x = int(input("Enter an odd positive number: "))
x = isValid(x)
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))