# Modules and Exception Handling
---
title: Agenda
description:
duration: 300
card_type: cue_card
---
### Agenda
* Modules in Python
* Random
* Math
* Exception Handling
* Try & Except
* Raising Custom Exceptions
---
title: Modules in Python
description:
duration: 900
card_type: cue_card
---
### Modules in Python
A module is a collection of python files that contains re-usable functions which can be imported to other files for use.
A collection of such modules is known as `Package`.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/019/835/original/Screenshot_2022-11-16_at_9.53.30_AM.png?1668572626">
\
Code:
```python=
# math is an in-built module in Python
import math
```
Code:
```python=
# Getting documentation of a module
# help(math)
```
Code:
```python=
# Calculating square root
math.sqrt(25)
```
Output:
```
5
```
\
Code:
```python=
# random is a built-in module in Python
import random
```
Code:
```python=
# Getting documentation of a module
# help(random)
```
Code:
```python=
# Generating a random number between 0 and 100
random.randint(0,100)
```
Output:
```
47
```
---
title: Random & Math modules
description:
duration: 1800
card_type: cue_card
---
### Random
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/019/836/original/Screenshot_2022-11-16_at_9.57.27_AM.png?1668572857" width="700" height="200">
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/019/837/original/Screenshot_2022-11-16_at_9.57.37_AM.png?1668572876" width="700" height="100">
\
Timestamp is a unique number that represents all the information regarding time and location and it keeps changing every unit time.
Code:
```python=
random.seed(100)
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
```
Output:
```
2
7
7
2
6
```
Code:
```python=
# Keeping the seed same will give the same set of random values.
random.seed(100)
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
```
Output:
```
2
7
7
2
6
```
Code:
```python=
# Changing the seed will change the pattern of the values being generated.
random.seed(10)
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
```
Output:
```
9
0
6
7
9
```
### Math
Code:
```python=
# import math
from math import *
```
Above syntax imported all the functions and classes present inside the `math` module.
Code:
```python=
sqrt(16)
```
Output:
```
4.0
```
Code:
```python=
floor(90.5)
```
Output:
```
90
```
Code:
```python=
ceil(1.43)
```
Output:
```
2
```
Problem with the above syntax occur when you have multiple functions with the same name.
Importing all will cause problem because Python will override the first import by second.
**Solution:** Importing using diffferent alias names.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/019/838/original/Screenshot_2022-11-16_at_10.05.07_AM.png?1668573309" width="700" height="400">
\
Code:
```python=
import math as m
# m is known as an alias for the math module
```
Above syntax is importing the `math` module under a different alias name.
Code:
```python=
m.sqrt(9)
```
Output:
```
3.0
```
Code:
```python=
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
```
### <u>***HOMEWORK***</u>
Create a custom math module with 4 functions -
- add
- subtract
- multiply
- divide
---
title: Quiz-1
description:
duration: 60
card_type: quiz_card
---
# Question
Which of the following codes can be used to get a random integer between 0 and 100?
# Choices
- [ ] math.randint(0, 100)
- [ ] random.range(0, 100)
- [x] random.randint(0, 100)
- [ ] math.range(0, 100)
---
title: Break & Doubt Resolution
description:
duration: 720
card_type: cue_card
---
#### Quiz-1 Explanation
- The randint function is used to generate a random integer within a specified range.
- The correct syntax is `random.randint(a, b)`, where **a** is the start of the range (**inclusive**) and **b** is the end of the range (**inclusive**).
- So, random.randint(0, 100) will generate a random integer between 0 and 100 (inclusive).
- The other options are incorrect because:
- **`math.randint(0, 100)`**: The randint function is not part of the math module. The correct module is random.
- **`random.range(0, 100)`**: There is no range function in the random module. The correct function is randint.
- **`math.range(0, 100)`**: Similar to the first incorrect choice, the range function is not part of the math module, and the correct module for generating random numbers is random.
### Break & Doubt Resolution
`Instructor Note:`
* Take this time (up to 5-10 mins) to give a short break to the learners.
* Meanwhile, you can ask the them to share their doubts (if any) regarding the topics covered so far.
---
title: Exception Handling
description:
duration: 1800
card_type: cue_card
---
### Exception Handling
When we make some errors in our code
* If Python knows what's causing it then that is known as an `Exception`.
* Rest all the errors that are unknown to Python are simply called `Errors`.
Code:
```python=
1 / 0
```
Output:
```
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-21-bc757c3fda29> in <cell line: 1>()
----> 1 1 / 0
ZeroDivisionError: division by zero
```
Code:
```python=
print(a_not_defined)
```
Output:
```
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-2bfecbfb1f8c> in <cell line: 1>()
----> 1 print(a_not_defined)
NameError: name 'a_not_defined' is not defined
```
Code:
```python=
if 573:
```
Output:
```
File "<ipython-input-24-236e0dbab875>", line 1
if 573:
^
SyntaxError: incomplete input
```
Code:
```python=
import module_random_which_does_not_exist
```
Output:
```
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-26-a132a4a652e6> in <cell line: 1>()
----> 1 import module_random_which_does_not_exist
ModuleNotFoundError: No module named 'module_random_which_does_not_exist'
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------
```
Code:
```python=
"random i am".sort()
```
Output:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-a913f33d29b2> in <cell line: 1>()
----> 1 "random i am".sort()
AttributeError: 'str' object has no attribute 'sort'
```
Code:
```python=
def something():
1 / 0
print("A")
something()
print("B")
```
Output:
```
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-27-7e95bf91f84a> in <cell line: 5>()
3 print("A")
4
----> 5 something()
6 print("B")
<ipython-input-27-7e95bf91f84a> in something()
1 def something():
----> 2 1 / 0
3 print("A")
4
5 something()
ZeroDivisionError: division by zero
```
**Note:** As the exception occurs, the rest of the code will not be executed.
---
title: Try & Except
description:
duration: 1200
card_type: cue_card
---
### Try & Except
In order to handle such `exceptions`, we need some conditional functions that can deal with them whenever they occur.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/019/839/original/Screenshot_2022-11-16_at_10.11.15_AM.png?1668573710" width="700" height="200">
\
Code:
```python=
def i_divide_by_zero(a):
return a / 0
try:
i_divide_by_zero(5)
5 + 4
# any amount of code
except:
print("Why are you dividing by zero?")
```
Output:
```
Why are you dividing by zero?
```
Code:
```python=
def i_divide_by_zero(a):
return a / 0
try:
# i_divide_by_zero(5)
print(5 + 4)
# any amount of code
except:
print("Why are you dividing by zero?")
```
Output:
```
9
```
Code:
```python=
# Getting what exception is occuring -
l1 = [2, 0, "hello", None]
for e in l1:
try:
print(f"Current element - {e}")
result = 5 / int(e)
print(f"Result - {result}")
except Exception as exp:
print(f"Excpetion - {exp}")
print("-"*50)
print("Execution Successful!")
```
Output:
```
Current element - 2
Result - 2.5
--------------------------------------------------
Current element - 0
Excpetion - division by zero
--------------------------------------------------
Current element - hello
Excpetion - invalid literal for int() with base 10: 'hello'
--------------------------------------------------
Current element - None
Excpetion - int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
--------------------------------------------------
Execution Successful!
```
Code:
```python=
# Handling different exceptions differently -
l1 = [2, 0, "hello", None]
for e in l1:
try:
print(f"Current element - {e}")
result = 5 / int(e)
print(f"Result - {result}")
except ZeroDivisionError as z:
print(f"You divided by zero. Number is {e}!")
except Exception as exp:
print(f"Exception - {exp}")
print("-"*50)
print("Execution Successful!")
```
Output:
```
Current element - 2
Result - 2.5
--------------------------------------------------
Current element - 0
You divided by zero. Number is 0!
--------------------------------------------------
Current element - hello
Exception - invalid literal for int() with base 10: 'hello'
--------------------------------------------------
Current element - None
Exception - int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
--------------------------------------------------
Execution Successful!
```
#### Any code within the `finally` block will be executed irrespective of whether an exception occurs or not.
Code:
```python=
try:
print("I am trying!")
1/0
except:
print("Exception")
finally:
print("FINALLY")
```
Output:
```
I am trying!
Exception
FINALLY
```
Code:
```python=
try:
print("I am trying!")
print(1/2)
except:
print("Except")
print("FINALLYYY!")
```
Output:
```
I am trying!
0.5
FINALLYYY!
```
### Any code within `finally` block will occur whether expetion occurs or not
Code:
```python=
try:
print("I am trying!")
print(1/2)
except:
print("Except")
print("FINALLYYY!")
```
Output:
```
I am trying!
0.5
FINALLYYY!
```
### <u>***HOMEWORK***</u>
Find out why `finally` exists when we can achieve same code structure using a print statement.
---
title: Raising Custom Exceptions
description:
duration: 600
card_type: cue_card
---
### Raising Custom Exceptions
Code:
```python=
raise Exception("This password is incorrect!")
```
Output:
```
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-36-06bd7c35b8f2> in <cell line: 1>()
----> 1 raise Exception("This password is incorrect!")
Exception: This password is incorrect!
```
Code:
```python=
raise ZeroDivisionError
```
Output:
```
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-39-c62fc6984c64> in <cell line: 1>()
----> 1 raise ZeroDivisionError
ZeroDivisionError:
```
Code:
```python=
num = 5
if num%2 != 0:
raise Exception("Number is odd!")
```
Output:
```
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-40-9e98b5a32062> in <cell line: 2>()
1 num = 5
2 if num%2 != 0:
----> 3 raise Exception("Number is odd!")
Exception: Number is odd!
```
Code:
```python=
class MyCustomException(Exception):
def __init__(self, message):
super().__init__(message)
name = "Sach"
try:
if len(name)<5:
raise MyCustomException("Length of name must be >4 characters")
else:
print("Name:", name)
except MyCustomException as e:
print(e)
```
Output:
```
Length of name must be >4 characters
```
---
title: Quiz-2
description:
duration: 60
card_type: quiz_card
---
# Question
What will be the output of the following code?
```
try:
assert False, "Error occurred!"
except AssertionError as e:
print(e)
```
# Choices
- [ ] AssertionError
- [x] Error occurred
- [ ] AssertionError: Error occurred!
- [ ] The program will terminate with no output.
---
title: Quiz-2 Explanation
description:
duration: 150
card_type: cue_card
---
#### Quiz-2 Explanation
- The **try** block attempts to execute the code inside it.
- The `**assert**` statement checks if the specified expression is True. In this case, the expression is False, so an **AssertionError** is raised.
- The **`except AssertionError as e:`** block catches the AssertionError exception and assigns it to the variable **e**.
- Inside the except block, **`print(e)`** is called, which prints the error message associated with the AssertionError.
---
title: Quiz-3
description:
duration: 60
card_type: quiz_card
---
# Question
In the code snippet below, why is the output "E" for the element 0 and not "Z"?
```python=
l1 = [2, 0, "hello", None]
for e in l1:
try:
result = 5 / int(e)
print("N")
except Exception as ex:
print("E")
except ZeroDivisionError as z:
print("Z")
```
# Choices
- [ ] ZeroDivisionError and Exception are distinct without a subclass relationship.
- [x] The "Z" block is placed after the "E" block.
- [ ] The exception for element 0 is not ZeroDivisionError.
- [ ] The code does not contain a ZeroDivisionError.
---
title: Quiz-3 Explanation
description:
duration: 150
card_type: cue_card
---
#### Quiz-3 Explanation
- In Python, when an exception occurs, the program looks for the first except block that can handle the exception, **based on the order in which they appear**.
- In the provided code snippet, the **`except Exception as ex`** block comes before the **`except ZeroDivisionError as z`** block.
- When the element is 0 in the loop, the line **`result = 5 / int(e)`** will raise a `ZeroDivisionError`.
- However, since the except Exception as ex block is encountered first, it will catch the exception, and the code will print "E" instead of "Z."
---
title: Practice Coding Question(s)
description:
duration: 600
card_type: cue_card
---
### Practice Coding Question(s)
You can pick the following question and solve it during the lecture itself.
This will help the learners to get familiar with the problem solving process and motivate them to solve the assignments.
<span style="background-color: red;">Make sure to start the doubt session before you start solving the question.</span>
Q. https://www.scaler.com/hire/test/problem/96651/