Piyush Ranjan
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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/

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully