Write down a try block that attempts to assign z = x//y. If a ZeroDivisionError
ID: 3809882 • Letter: W
Question
Write down a try block that attempts to assign z = x//y. If a ZeroDivisionError occurs, your code should print "Error Code 1" If some other error occurs, your code should print "Error Code 2" If no error occurs, your code should print "z was successfully assigned." Lastly, no matter what happens, your code should print "end of program reached '. You should *not* use if statements for this problem, only try. except, else, and finally as needed. b) It is often useful to anticipate what kinds of errors can occur in a piece of code. Name at least four exceptions that could occur from the following lines of code, and identify which line it could occur in. You *can* consider the possibility that new_mod or random.string or m is not defined, hut you should assume that if new mod and random string are defined then they won't cause any errors by themselves. (line 1) >>> import new_mod (line 2) >>> ranstr = newmod.random_string() (line 3) >>> assert type(ranstr) == str (line 4) >>> n = len(ranstr) % mExplanation / Answer
Question1
##Assign value for x and y - try to change the value to see the difference - try to excute each of the input set
##input set1
x=6
y=2
##input set2
##x=5
##y="str1"
##input set3
##x=4
##y=0
try:
z=x//y
except ZeroDivisionError:
print("Error code 1")
except:
print("Error Code 2")
else:
print("z was successfully assigned")
finally:
print("end of program reached")
Question 2
##Please try to execute each error by creating 2 different file in same folder, Sample.py and new_mod.(for first error do not create new_mod.py)
##Error1:
##Assume new_mod is not defined
##at line 1 : ImportError: No module named new_mod
##Sample.py
import new_mod
ranstr=newmod.random_string()
assert type(ranstr)==str
n=len(ranstr)%m
##Error2
##at line 2 : NameError: name 'newmod' is not defined
##Assume new_mod is defined
##new_mod.py
def random_string():
pass
##Sample.py
import new_mod
ranstr=newmod.random_string()
assert type(ranstr)==str
n=len(ranstr)%m
##Error3
##at line 3 : AssertionError(If returned value is not of type string )
##Defined new_mod and imported as newmod in current program
##new_mod.py
def random_string():
pass
##Sample.py
import new_mod as newmod
ranstr=newmod.random_string()
assert type(ranstr)==str
n=len(ranstr)%m
##Error4
##as line 4 : NameError: name 'm' is not defined
##Defined new_mod and renamed that as newmod in current program
##new_mod.py
def random_string():
return ("Hi")
##Sample.py
import new_mod as newmod
ranstr=newmod.random_string()
assert type(ranstr)==str
n=len(ranstr)%m
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.