In [9]:
try:
x= 10/0
# code with possible error (exceptions)
except ZeroDivisionError:
print('Divide by zero')
x = None
# handling error
print(x)
Divide by zero None
In [16]:
lst = [1,2,3,4,5]
try:
print(lst[10])
except IndexError: # handle specific exception
print('Out of range')
lst[10]
Out of range
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-16-1c2b54f067d2> in <cell line: 7>() 5 print('Out of range') 6 ----> 7 lst[10] IndexError: list index out of range
In [13]:
try:
num = int(input('Enter a number: '))
except ValueError: # handle specific exception
print('Not a number')
else: # if no exception
print(num)
Enter a number: 5 5
In [15]:
try:
num = int(input('Enter a number: '))
except ValueError: # handle specific exception
print('Not a number')
else: # if no exception
print(num)
finally: # always
print('This is always executed')
Enter a number: 5 5 This is always executed
In [19]:
x = -1
if x < 0:
raise ValueError("Sorry, no numbers below zero")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-19-ce3195fd66fa> in <cell line: 3>() 2 3 if x < 0: ----> 4 raise ValueError("Sorry, no numbers below zero") ValueError: Sorry, no numbers below zero
In [18]:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-18-bc91768a6271> in <cell line: 3>() 2 3 if not type(x) is int: ----> 4 raise TypeError("Only integers are allowed") TypeError: Only integers are allowed
In [20]:
def divide(x, y):
# try:
# result = x // y
# except ZeroDivisionError:
# print("Sorry ! You are dividing by zero ")
# else:
# print("Yeah ! Your answer is :", result)
divide(5,0)
Sorry ! You are dividing by zero
In [22]:
def divide(x, y):
'''This function divides two numbers
Inputs:
x: int
y: int
Output:
result: float
'''
assert y != 0
assert type(x) == int and type(y) == int, 'Wrong type'
return x / y
divide(5,1.)
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-22-972854fe6427> in <cell line: 6>() 4 return x / y 5 ----> 6 divide(5,1.) <ipython-input-22-972854fe6427> in divide(x, y) 1 def divide(x, y): 2 assert y != 0 ----> 3 assert type(x) == int and type(y) == int, 'Wrong type' 4 return x / y 5 AssertionError: Wrong type
In [27]:
def copy(L1,L2):
''' Assumes L1,L2 are lists
Mutates L2 to be a copy of L1
'''
while len(L2) > 0:
L2.pop()
for e in L1:
L2.append(e)
L1 = [1,2,3]
L2 = [4,5,6]
copy(L1,L2)
print(L2)
#
[None]
In [29]:
L1 = [1,2,3]
copy(L1,L1)
print(L1)
[]