0% found this document useful (0 votes)
24 views346 pages

Python Unit 3

The document provides an overview of error handling in Python, detailing types of errors such as syntax errors, runtime errors, and logical errors. It explains how exceptions can disrupt program execution and introduces exception handling mechanisms like try-except blocks. Additionally, it covers custom exceptions, the use of the raise keyword, and the advantages and disadvantages of exception handling.

Uploaded by

mycomfzone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views346 pages

Python Unit 3

The document provides an overview of error handling in Python, detailing types of errors such as syntax errors, runtime errors, and logical errors. It explains how exceptions can disrupt program execution and introduces exception handling mechanisms like try-except blocks. Additionally, it covers custom exceptions, the use of the raise keyword, and the advantages and disadvantages of exception handling.

Uploaded by

mycomfzone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

Error Handling

Computer Applications
PROGRAMMING WITH PYTHON
Error Handling

• Errors are caused by problems with the syntax or structure of the program.

• They typically occur before the program is even run, and they prevent the

program from being executed at all.

• Errors in Python generally denote more serious problems that typically

cannot be handled gracefully during runtime.

• These can often lead to the termination of the program.


PROGRAMMING WITH PYTHON
Error Handling

• Error in Python can be of two types

• Syntax errors

• Logical Errors

• Errors are problems in a program due to which the program will stop the

execution.
PROGRAMMING WITH PYTHON
Syntax Errors

• A syntax error occurs in Python when the interpreter is unable to parse the

code due to the code violating Python language rules such as

• inappropriate indentation

• erroneous keyword usage

• incorrect operator use.


PROGRAMMING WITH PYTHON
Syntax Errors

• Syntax errors prohibit the code from running, and the interpreter displays an

error message that specifies the problem and where it occurred in the code.
PROGRAMMING WITH PYTHON
Runtime Errors

• In Python, a runtime error occurs when the program is executing and

encounters an unexpected condition that prevents it from continuing.


PROGRAMMING WITH PYTHON
Runtime Errors

• Runtime errors are also known as exceptions and can occur for various

reasons such as

• division by zero

• attempting to access an index that is out of range

• calling a function that does not exist.


PROGRAMMING WITH PYTHON
Logical Errors

• A logical error occurs in Python when the code runs without any syntax or

runtime errors but produces incorrect results due to flawed logic in the code.
PROGRAMMING WITH PYTHON
Logical Errors

• These types of errors are often caused by

• incorrect assumptions

• an incomplete understanding of the problem

• or the incorrect use of algorithms or formulas.


PROGRAMMING WITH PYTHON
Logical Errors

• Unlike syntax or runtime errors, logical errors can be challenging to

detect and fix because the code runs without producing any error

messages.

• The results may seem correct, but the code might produce incorrect

output in certain situations.


PROGRAMMING WITH PYTHON
Logical Errors


PROGRAMMING WITH PYTHON
Logical Errors


PROGRAMMING WITH PYTHON
Errors handled in Python


PROGRAMMING WITH PYTHON
Runtime Errors


PROGRAMMING WITH PYTHON
Name Error

• A NameError in Python is raised when the interpreter encounters a variable

or function name that it cannot find in the current scope.

• This can happen for a variety of reasons

• misspelling a variable or function name

• using a variable or function before it is defined

• referencing a variable or function that is outside the current scope.


PROGRAMMING WITH PYTHON
Name Error


PROGRAMMING WITH PYTHON
Type Error

• The error is raised when an operation or function is applied to an object of

an inappropriate type.

• Performing arithmetic or logical operations on incompatible data types

• Passing arguments of the wrong type to a function.


PROGRAMMING WITH PYTHON
Type Error


PROGRAMMING WITH PYTHON
Index Error

• The error is raised in Python when an index of a sequence (such as a string,

list, or tuple) that is out of range is tried to be accessed.

• Trying to access an element that doesn't exist in the sequence

• Trying to access an element at an index that is greater than or equal to

the length of the sequence.


PROGRAMMING WITH PYTHON
Index Error


PROGRAMMING WITH PYTHON
Attribute Error

• The error is raised when an attribute or method of an object is accessed that does

not exist or is not defined for that object.

• Misspelling the name of an attribute or method

• Trying to access an attribute or method that is not defined for the type of object

that is being worked with.


PROGRAMMING WITH PYTHON
Attribute Error


PROGRAMMING WITH PYTHON
Floating Point Error

• It is a type of numerical error that occurs when representing real numbers in a

computer.

• This is because computers can only store a finite number of digits, so they must

approximate real numbers using a fixed number of bits.

• This approximation can introduce errors, which can accumulate over time.
PROGRAMMING WITH PYTHON
Floating Point Error


PROGRAMMING WITH PYTHON
Key Error

• It is an error when a key is not found in a dictionary.


PROGRAMMING WITH PYTHON
Overflow Error

• The error is raised when the result of an arithmetic operation is too large to be

represented.
PROGRAMMING WITH PYTHON
Value Error

• The error is raised when a function gets an argument of correct type but improper

value.
PROGRAMMING WITH PYTHON
Keyboard Interrupt Error

• The error is raised when the user does not complete the input method.
PROGRAMMING WITH PYTHON
Unbound Local Error

• The UnboundLocalError occurs when a local variable is referenced before it

has been assigned a value within a function or method.


PROGRAMMING WITH PYTHON
Unbound Local Error
PROGRAMMING WITH PYTHON
Recap

• Error Handling

• Types of errors

• Syntax Errors

• Logical Errors

• Runtime Errors

• Errors handled in Python


THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

Exceptions

Computer Applications
PROGRAMMING WITH PYTHON
Exceptions

• An exception is an unexpected event that occurs during program execution.

• These events can disrupt the normal flow of the program and potentially

cause it to crash.

• To handle exceptions effectively, Python provides a mechanism called

exception handling, which allows programmers to anticipate and deal with

potential errors gracefully.


PROGRAMMING WITH PYTHON
Exceptions

• They represent errors or exceptional conditions that arise when a script

is running.

• When an exceptional event occurs in Python, an object known as an

"exception" is raised.

• This object contains information about the error, such as its type and,

often, additional data about what went wrong.


PROGRAMMING WITH PYTHON
Exceptions

• Exception handling involves two main components

• Raising exceptions

• Handling exceptions.
PROGRAMMING WITH PYTHON
Exceptions

• Raising Exceptions

• Raising an exception is the process of notifying the program that an error

has occurred.

• This is done using the raise keyword followed by an exception object.


PROGRAMMING WITH PYTHON
Exceptions

• Handling Exceptions

• Handling exceptions involves using the try and except blocks.

• The try block contains the code that needs to be monitored for potential

errors.

• The except block contains the code that should be executed when an

exception is raised.
PROGRAMMING WITH PYTHON
Exceptions

• There are built-in exceptions in Python that are raised when corresponding

errors occur.

• It can be viewed using

• print(dir(locals()['__builtins__']))
PROGRAMMING WITH PYTHON
Try .. except block

• The try...except block is used to handle exceptions in Python.

• try:

• # code that may cause exception

• except:

• # code to run when exception occurs


PROGRAMMING WITH PYTHON
Try .. except block


PROGRAMMING WITH PYTHON
Try .. except block

• To handle the exception, put the code, result = numerator/denominator

inside the try block.

• Now when an exception occurs, the rest of the code inside the try block is

skipped.
PROGRAMMING WITH PYTHON
Try .. except block

• The except block catches the exception and statements inside the except

block are executed.

• If none of the statements in the try block generates an exception, the except

block is skipped.
PROGRAMMING WITH PYTHON
Try .. except block


PROGRAMMING WITH PYTHON
Try .. except block


PROGRAMMING WITH PYTHON
Try .. else block

• To run a certain block of code if the code block inside try runs without

any errors.

• For these cases, use the optional else keyword with the try statement.
PROGRAMMING WITH PYTHON
Try .. else block


PROGRAMMING WITH PYTHON
Try .. finally block

• The finally block is always executed no matter whether there is an exception

or not.

• The finally block is optional.

• For each try block, there can be only one finally block.
PROGRAMMING WITH PYTHON
Try .. finally block


PROGRAMMING WITH PYTHON
Recap

• Exceptions

• Try Except

• Try Else

• Try Finally
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

User-defined Exceptions

Computer Applications
PROGRAMMING WITH PYTHON
Custom Exceptions

• Define custom exceptions by creating a new class that is derived from the

built-in Exception class.


PROGRAMMING WITH PYTHON
Custom Exceptions

• class CustomError(Exception):

• ...

• try:

• ...

• except CustomError:

• ...
PROGRAMMING WITH PYTHON
Custom Exceptions


PROGRAMMING WITH PYTHON
Custom Exceptions


PROGRAMMING WITH PYTHON
Custom Exceptions


PROGRAMMING WITH PYTHON
Raise Exceptions

• Python also provides the raise keyword to be used in the context of

exception handling.

• It causes an exception to be generated explicitly.

• Built-in errors are raised implicitly.

• However, a built-in or custom exception can be forced during execution.


PROGRAMMING WITH PYTHON
Raise Exceptions

• The raise statement in Python is used to raise an exception.

• Try-except blocks can be used to manage exceptions, which are errors that

happen while a programme is running.

• When an exception is triggered, the program goes to the closest exception

handler, interrupting the regular flow of execution.


PROGRAMMING WITH PYTHON
Raise Exceptions

• The raise keyword is typically used inside a function or method, and is used

to indicate an error condition.

• An exception can be thrown and immediately halt the running of the

program by using the raise keyword.

• Python looks for the closest exception handler, which is often defined using a

try-except block, when an exception is triggered.


PROGRAMMING WITH PYTHON
Raise Exceptions

• If an exception handler is discovered, its code is performed, and the try-

except block's starting point is reached again.

• If an exception handler cannot be located, the software crashes and an error

message appears.
PROGRAMMING WITH PYTHON
Raise Exceptions


PROGRAMMING WITH PYTHON
Raise Exceptions


PROGRAMMING WITH PYTHON
Raise Exceptions


PROGRAMMING WITH PYTHON
Raise Exceptions


PROGRAMMING WITH PYTHON
Raise Exceptions


PROGRAMMING WITH PYTHON
Advantages of Exceptions

• Improved program reliability

• By handling exceptions properly, prevent the program from crashing or

producing incorrect results due to unexpected errors or input.

• Simplified error handling

• Exception handling allows the separation of error handling code from the

main program logic, making it easier to read and maintain the code.
PROGRAMMING WITH PYTHON
Advantages of Exceptions

• Cleaner code

• With exception handling, avoid using complex conditional statements to

check for errors, leading to cleaner and more readable code.


PROGRAMMING WITH PYTHON
Advantages of Exceptions

• Easier debugging

• When an exception is raised, the Python interpreter prints a traceback

that shows the exact location where the exception occurred, making it

easier to debug the code.


PROGRAMMING WITH PYTHON
Disadvantages of Exceptions

• Performance overhead

• Exception handling can be slower than using conditional statements to

check for errors, as the interpreter has to perform additional work to

catch and handle the exception.


PROGRAMMING WITH PYTHON
Disadvantages of Exceptions

• Increased code complexity

• Exception handling can make the code more complex, especially if there

is a need to handle multiple types of exceptions or implement complex

error handling logic.


PROGRAMMING WITH PYTHON
Disadvantages of Exceptions

• Possible security risks

• Improperly handled exceptions can potentially reveal sensitive

information or create security vulnerabilities in the code, so it’s important

to handle exceptions carefully and avoid exposing too much information

about the program.


PROGRAMMING WITH PYTHON
Recap

• Custom Exceptions

• Raise Exceptions

• Advantages of Exceptions

• Disadvantages of Exceptions
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

File Handling – Text

Computer Applications
PROGRAMMING WITH PYTHON
File Handling

• Python supports the file-handling process.

• The input was taken from the console and written back to the console to

interact with the user.

• Users can easily handle the files, like read and write the files in Python.

• File handling is also effortless and short in Python.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Open the file using Python's built-in open() function.

• This function creates a file object, which would be utilized to call other

support methods associated with it.

• file object = open(file_name [, access_mode][, buffering])


PROGRAMMING WITH PYTHON
File Handling – Text Files

• file_name

• The file_name argument is a string value that contains the name of the

file that is accessed.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• access_mode

• The access_mode determines the mode in which the file has to be

opened, i.e., read, write, append, etc.

• This is optional parameter and the default file access mode is read (r).
PROGRAMMING WITH PYTHON
File Handling – Text Files

• Description
r Opens a file for reading only.
The file pointer is placed at the beginning of the file.
This is the default mode.
r+ Opens a file for both reading and writing.
The file pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
PROGRAMMING WITH PYTHON
File Handling – Text Files

• Description
w+ Opens a file for both writing and reading.
Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending.
The file pointer is at the end of the file if the file exists.
If the file does not exist, it creates a new file for writing.
PROGRAMMING WITH PYTHON
File Handling – Text Files

• Description
a+ Opens a file for both appending and reading.
The file pointer is at the end of the file if the file exists.
If the file does not exist, it creates a new file for reading and writing.
PROGRAMMING WITH PYTHON
File Handling – Text Files

• buffering

• If the buffering value is set to 0, no buffering takes place.

• If the buffering value is 1, line buffering is performed while accessing a file.

• If the buffering value is specified as an integer greater than 1, then buffering

action is performed with the indicated buffer size.

• If negative, the buffer size is the system default(default behavior).


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read a file

• [Link](size)

• Size

• An integer that specifies the number of bytes to read from the file.

• If omitted or set to -1, it reads the entire file.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read a file

• [Link](size)

• Returns a string containing the data read from the file

• Returns an empty string if read beyond the end of file


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read a line

• [Link](size=-1)

• size

• An integer that specifies the maximum number of characters (or

bytes in binary mode) to read from the line.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read a line

• [Link](size=-1)

• size

• If size is omitted or set to -1, it reads the entire line, up to the newline

character (\n).

• If the specified size is smaller than the length of the line, only size

characters will be returned.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read a line

• Output is a string representing the line read from the file.

• Includes the newline character (\n) at the end of the line unless the end of

the file is reached or the line is shorter than size.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read line by line

• [Link](hint=-1)

• hint

• An integer specifying the maximum number of bytes to read.

• If omitted or set to -1, it reads all lines from the file.

• Useful for limiting the amount of data read into memory.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Read line by line

• [Link](hint=-1)

• It returns a list of strings, where each string represents a line in the file

(including the newline character \n).


PROGRAMMING WITH PYTHON
File Handling – Text Files

Function Reads Returns Usecase


read() Entire file or Single string Use when whole
specified characters content is needed as
one block.
readline() One line at a time Single string (one Use when processing
line) one line at a time.
readlines() All lines at once List of strings (each Use when all lines are
line) needed as separate
items.
PROGRAMMING WITH PYTHON
File Handling – Text Files

• Write text

• [Link](string)

• The string to be written to the file.

• It returns the number of characters written.


PROGRAMMING WITH PYTHON
File Handling – Text Files

• Write a text

• [Link](iterable)

• An iterable (e.g., list or tuple) of strings to be written to the file.

• Each string in the iterable is written as-is without adding a newline unless

explicitly included.
PROGRAMMING WITH PYTHON
File Handling – Text Files

Feature write() writelines()


Writes a single string to the Writes multiple strings from an
Purpose
file. iterable to the file.
An iterable of strings (e.g., list,
Input A single string.
tuple).
No, unless included in the No, unless included in each
Adds Newline
string. string in the iterable.
PROGRAMMING WITH PYTHON
File Handling – Text Files


PROGRAMMING WITH PYTHON
File Handling – Text Files
PROGRAMMING WITH PYTHON
File Handling – Text Files
PROGRAMMING WITH PYTHON
File Handling – Text Files
PROGRAMMING WITH PYTHON
File Handling – Text Files
PROGRAMMING WITH PYTHON
File Handling – Text Files
PROGRAMMING WITH PYTHON
Recap

• File handling

• Text Files
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

File I/O Operations - Excel

Computer Applications
PROGRAMMING WITH PYTHON
Excel

• Openpyxl is a Python library that enables users to read and write Excel files.

• This framework assists in creating functions, formatting spreadsheets,

generating reports, and constructing charts directly within Python,

eliminating the need to open an Excel application.

• Openpyxl permits users to navigate through worksheets and conduct

identical analyses on various data sets simultaneously.


PROGRAMMING WITH PYTHON
Excel


PROGRAMMING WITH PYTHON
Excel


PROGRAMMING WITH PYTHON
Excel


PROGRAMMING WITH PYTHON
Excel


PROGRAMMING WITH PYTHON
Excel


PROGRAMMING WITH PYTHON
Excel


PROGRAMMING WITH PYTHON
Excel

• Code sets the row and column positions of the starting cell for the sales figures.

• The row_position variable is set to 2, which means the sales figures are in the second row of the

spreadsheet.

• The col_position variable is set to 7, which means the sales figures start in the seventh column of

the spreadsheet.
PROGRAMMING WITH PYTHON
Excel

• The [Link]() method is used to access each cell, with the row and column

parameters specifying the position of each cell.


PROGRAMMING WITH PYTHON
Excel
PROGRAMMING WITH PYTHON
Excel
PROGRAMMING WITH PYTHON
Excel
PROGRAMMING WITH PYTHON
Excel
PROGRAMMING WITH PYTHON
Excel
PROGRAMMING WITH PYTHON
Recap

• Openpyxl

• Usage
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

File Handling – CSV files

Computer Applications
PROGRAMMING WITH PYTHON
File Handling – CSV Files

• CSV – comma separated values

• To work import csv


PROGRAMMING WITH PYTHON
File Handling – CSV Files

• The [Link]() function in Python is used to read data from a CSV file.

• It parses the file content and provides an iterable object that can be looped

through to access the rows in the file.


PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters

• file

• Required parameter

• The file object to be read, opened in text mode ('r') or binary mode ('rb').
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters

• delimiter

• Optional

• A single character that separates fields in the file.

• Default is a comma (,).

• [Link](file, delimiter=';')
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters

• skipinitialspace

• Optional

• A boolean value. If True, whitespace after the delimiter is ignored.

• Default is False.

• [Link](file, skipinitialspace=True)
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters

• skipinitialspace

• Optional

• A boolean value. If True, whitespace after the delimiter is ignored.

• Default is False.

• [Link](file, skipinitialspace=True)
PROGRAMMING WITH PYTHON
File Handling – CSV Files


PROGRAMMING WITH PYTHON
File Handling – CSV Files


PROGRAMMING WITH PYTHON
File Handling – CSV Files


PROGRAMMING WITH PYTHON
File Handling – CSV Files


PROGRAMMING WITH PYTHON
File Handling – CSV Files

• [Link]() function reads a CSV file and maps each row to a dictionary.

• The keys of the dictionary are derived from the header (first row) of the file,

and the values are the corresponding data for each row.

• [Link](file, fieldnames=None, restkey=None, restval=None,

dialect='excel', **optional_parameters)
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters

• delimiter: Character separating fields (default is ,).

• quotechar: Character used to quote fields (default is ").

• escapechar: Character used to escape delimiters in quoted fields.

• skipinitialspace: Ignore whitespace after the delimiter.


PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters

• delimiter: Character separating fields (default is ,).

• quotechar: Character used to quote fields (default is ").

• escapechar: Character used to escape delimiters in quoted fields.

• skipinitialspace: Ignore whitespace after the delimiter.


PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters
PROGRAMMING WITH PYTHON
File Handling – CSV Files - Parameters
PROGRAMMING WITH PYTHON
File Handling – CSV Files
PROGRAMMING WITH PYTHON
File Handling – CSV Files
PROGRAMMING WITH PYTHON
File Handling – CSV Files

• The [Link]() function in Python, provided by the csv module, is used to

write data to a CSV file.

• It provides an easy way to write rows of data in a comma-separated (or

otherwise delimited) format.


PROGRAMMING WITH PYTHON
File Handling – CSV Files

• Common Formatting Parameters

• Delimiter

• Specifies the character separating fields (default is ',').

• Quotechar

• Specifies the character used to quote fields (default is '"').


PROGRAMMING WITH PYTHON
File Handling – CSV Files

• Common Formatting Parameters:

• quoting: Controls quoting behavior.

• csv.QUOTE_MINIMAL (default): Quotes fields only when necessary.

• csv.QUOTE_ALL: Quotes all fields.

• csv.QUOTE_NONNUMERIC: Quotes all non-numeric fields.

• csv.QUOTE_NONE: No quoting; raises an error if fields contain special

characters.
PROGRAMMING WITH PYTHON
File Handling – CSV Files

• Common Formatting Parameters:

• Lineterminator

• Specifies the string used to terminate lines (default is '\r\n' on

Windows, '\n' on others).


PROGRAMMING WITH PYTHON
File Handling – CSV Files
PROGRAMMING WITH PYTHON
File Handling – CSV Files
PROGRAMMING WITH PYTHON
File Handling – CSV Files

writerow() writerows()
Functionality Writes a single row. Writes multiple rows at once.
Input A single iterable (e.g., list). An iterable of iterables (e.g., list of
lists).
Usage For writing one row at a For batch-writing multiple rows.
time.
PROGRAMMING WITH PYTHON
Recap

• File handling CSV files


THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

File I/O Operations - JSON

Computer Applications
PROGRAMMING WITH PYTHON
JSON

• JSON stands for JavaScript Object notation and is an open standard

human readable data format.

• JSON is written as key and value pair.

• An empty JSON file simply contains two curly braces {}.

• Multiple value statements in JSON are separated by a comma sign.


PROGRAMMING WITH PYTHON
JSON

• The Syntax rules for JSON is given below

• The data is simply a name value pair

• Data/Object/arrays are separated by comma

• Curly braces hold object

• Square holds array


PROGRAMMING WITH PYTHON
JSON

• JSON with {}

• It is stored as an object.

• Key value pairs are used.

• The program reads it like a dictionary.


PROGRAMMING WITH PYTHON
JSON

• Example

• { "name": “Alpha", "age": 21}

• It can be accessed as data["name"], data["age”]

• Or

• for k, v in [Link]():

• print(k, v)
PROGRAMMING WITH PYTHON
JSON

• JSON with []

• It is stored as an array.

• Multiple objects are kept inside.

• The program reads it like a list.


PROGRAMMING WITH PYTHON
JSON

• Example

• [ {"name": "Alpha, "age": 21},

• {"name": "Beta", "age": 20},

• {"name " : " Gamma", "age“: 18}]

• It can be accessed as

• data[0]["name”], data[0]["age"]
PROGRAMMING WITH PYTHON
JSON

• It can be accessed as

• for entry in data:

• print(entry["name"], entry["age"])

• Or

• names = [entry["name"] for entry in data]


PROGRAMMING WITH PYTHON
JSON

• A JSON file can start with {} and still contain multiple dictionaries, but they

must be stored as keyed dictionaries inside one main dictionary, not as a list

of separate objects.
PROGRAMMING WITH PYTHON
JSON

• JSON allows only one top-level value, and that top-level value can be

• one object (starts with {}) or

• one array (starts with [])

• If it starts with {}, everything inside must be structured as key value pairs.

• Multiple dictionaries must be placed under different keys.


PROGRAMMING WITH PYTHON
JSON

• Example

• {

• "alpha": {"age": 21, "city": ["Mangalore", "Bantwal"] },

• “beta": {"age": 20, "city": "Mysore"},

• “gamma": {"age": 18, "city": "Bangalore"}

• }
PROGRAMMING WITH PYTHON
JSON

• Code can access the data

• data["emp1"]["salary"]

• Or

• for key in data:

• entry = data[key]

• print(entry["name"], entry["salary"])
PROGRAMMING WITH PYTHON
JSON

• In Python, JSON exists as a string.

• Example

• p = '{"name": "Bob", "languages": ["Python", "Java"]}'

• It's also common to store a JSON object in a file.


PROGRAMMING WITH PYTHON
JSON

• [Link]()

• Reads JSON data from a file-like object and deserializes it into a

corresponding Python object.

• [Link]()

• Deserializes a JSON-formatted string into a corresponding Python object.


PROGRAMMING WITH PYTHON
JSON

• [Link]()

• Serializes a Python object and writes it as JSON data to a file-like object.

• [Link]()

• Serializes a Python object into a JSON-formatted string.


PROGRAMMING WITH PYTHON
JSON

• Parse a JSON string


PROGRAMMING WITH PYTHON
JSON

• Read a file containing JSON object and parse the data into a dictionary

called data in the example


PROGRAMMING WITH PYTHON
JSON


PROGRAMMING WITH PYTHON
JSON

• Convert the dictionary to JSON


PROGRAMMING WITH PYTHON
JSON

• Write JSON to a file in Python


PROGRAMMING WITH PYTHON
JSON

• Pass additional parameters indent and sort_keys to [Link]() and

[Link]() method.


PROGRAMMING WITH PYTHON
JSON

• Count the lines to store the students' addresses. Store these values in a

list with the person’s name and print the list.


PROGRAMMING WITH PYTHON
JSON

• Store only the mappings between the students’ names and their phone

numbers.


PROGRAMMING WITH PYTHON
Recap

• JSON files

• Syntax

• Reading a JSON file

• Writing a JSON file

• Converting Dictionary to JSON


THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

File I/O Operations - XML

Computer Applications
PROGRAMMING WITH PYTHON
XML Files

• The Extensible Markup Language (XML) is a markup language much like

HTML.

• It is a portable.

• It is useful for handling small to medium amounts of data without

using any SQL database.


PROGRAMMING WITH PYTHON
XML Files

• Python's standard library contains xml package.

• This package has following modules that define XML processing APIs.

• [Link]: a simple and lightweight XML processor API

• [Link]: the DOM API definition

• [Link]: SAX2 base classes and convenience functions


PROGRAMMING WITH PYTHON
XML Files - ElementTree module

• XML is a tree like hierarchical data format.

• This module has two classes for this purpose

• 'ElementTree' treats the whole XML document as a tree

• 'Element' represents a single node in this tree.


PROGRAMMING WITH PYTHON
XML Files - ElementTree module

Import the package

List of books with attributes and elements


Create the root element
PROGRAMMING WITH PYTHON
XML Files - ElementTree module

• Iterate through the


books list to build
the XML tree
PROGRAMMING WITH PYTHON
XML Files – Tree Structure

• Root Element

• The topmost element of the XML document.

• Every XML document has exactly one root element.

• <bookstore>: bookstore is the root.


PROGRAMMING WITH PYTHON
XML Files - Tree Structure

• Parent Element

• An element that contains one or more child elements.

• In <book><title>Pride and Prejudice</title></book>, book is the

parent of title.
PROGRAMMING WITH PYTHON
XML Files - Tree Structure

• Child Element

• An element that is nested inside a parent element.

• In <book><title>Pride and Prejudice</title></book>, title is the

parent of title.
PROGRAMMING WITH PYTHON
XML Files - Tree Structure

• Sibling Elements

• Elements that share the same parent.

• In <book><title>Pride and Prejudice</title><author>Jane

Austen</author></book>, title and author are siblings


PROGRAMMING WITH PYTHON
XML Files - Tree Structure

• Attributes

• Name-value pairs associated with an element.

• Attributes are not considered nodes but are part of the element.

• <book category="fiction"> where category="fiction" is an attribute


PROGRAMMING WITH PYTHON
XML Files – XML Files – ElementTree Module

• Parsing an XML File


Import the package

Parse the XML file and initialize


an empty list to store book
details
PROGRAMMING WITH PYTHON
XML Files – XML Files – ElementTree Module

• Parsing an XML File

Iterate over each 'book' element in the XML, Extract the category attribute,
Extract the child elements: title, author and price, Append the extracted book
details to the books list and Print the parsed books data
PROGRAMMING WITH PYTHON
XML Files – XML Files – ElementTree Module
PROGRAMMING WITH PYTHON
XML Files – XML Files – ElementTree Module

• Modifying an XML File


Iterate over each 'price'
element in the XML, Convert
the price to an integer,
increment by 10, and update
the text
PROGRAMMING WITH PYTHON
XML Files – XML Files – ElementTree Module

• Modifying an XML File


Save the modified XML back to
the file
PROGRAMMING WITH PYTHON
Recap

• XML Files

• File Handling - Element Tree

• Operations

• Reading

• Writing

• Modifying
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

Pandas DataFrame Operations

Computer Applications
PROGRAMMING WITH PYTHON
Pandas

• Pandas is a popular Python package for data science.

• It offers powerful, expressive and flexible data structures that make

data manipulation and analysis easy.


PROGRAMMING WITH PYTHON
DataFrame

• They are defined as two-dimensional labelled data structures with columns

of potentially different types.

• Pandas DataFrame consists of three main components

• Data

• Index

• Columns
PROGRAMMING WITH PYTHON
DataFrame - Creation

• A Pandas DataFrame can be created

• Using Python Dictionary

• Using Python List

• From a File

• Creating an Empty DataFrame


PROGRAMMING WITH PYTHON
DataFrame


PROGRAMMING WITH PYTHON
DataFrame


PROGRAMMING WITH PYTHON
DataFrame

• Inspect head, tail, shape and columns

• The first few rows are viewed with [Link]().

• The last few rows are viewed with [Link]().

• The total size is checked with [Link].

• Column names are checked with [Link].

• The index is checked with [Link].


PROGRAMMING WITH PYTHON
DataFrame
PROGRAMMING WITH PYTHON
DataFrame

• Column data types are checked with [Link].

• One column is converted to a different type.


PROGRAMMING WITH PYTHON
DataFrame

• Select columns and rows with loc and iloc.

• Rows by label are selected using loc.


PROGRAMMING WITH PYTHON
DataFrame

• Rows by integer position are selected using iloc.

• Row and column together are selected.


PROGRAMMING WITH PYTHON
DataFrame

• Check for missing values per column using [Link]().

• Rows with missing values are checked using [Link]().any(axis=1).sum()

• notna() is tried to see non-missing positions.


PROGRAMMING WITH PYTHON
DataFrame

• Missing values in that column are filled with the mean or median.
PROGRAMMING WITH PYTHON
DataFrame

• Missing values in that column are filled with the mean or median.
PROGRAMMING WITH PYTHON
DataFrame

• Drop a column
PROGRAMMING WITH PYTHON
DataFrame

• Standardize text columns


PROGRAMMING WITH PYTHON
DataFrame

• Rename columns for clarity

• Column names are printed with [Link].

• Can create a rename dictionary.

• Example: rename_map = {"Prod": "Product", "Qty": "Quantity"}

• df = [Link](columns=rename_map) is applied

• Columns are checked again to confirm clean names.


PROGRAMMING WITH PYTHON
DataFrame

• Rename columns for clarity

• Column names are printed with [Link].

• Can create a renamed dictionary.

• Example: rename_map = {"Prod": "Product", "Qty": "Quantity"}

• df = [Link](columns=rename_map) is applied
PROGRAMMING WITH PYTHON
DataFrame

• Convert numeric text columns to proper numbers

• A column that looks numeric but is stored as object is identified.

• Example: df["Amount"].dtype is checked.

• Non-numeric characters are removed if needed.

• Example: df["Amount"] = df["Amount"].[Link](",", "")


PROGRAMMING WITH PYTHON
DataFrame

• Convert numeric text columns to proper numbers

• The column is converted to float or int.

• Example: df["Amount"] = df["Amount"].astype("float64")

• dtypes is checked again to confirm numeric type.


PROGRAMMING WITH PYTHON
DataFrame


PROGRAMMING WITH PYTHON
DataFrame

• Filter the data


PROGRAMMING WITH PYTHON
DataFrame

• Combine multiple conditions.

• They are combined with & and |.


PROGRAMMING WITH PYTHON
DataFrame

• Sort values by one or more columns.

• Example: The DataFrame is sorted by "Amount".

• df_sorted = df.sort_values("Amount", ascending=False)

• Sorting by multiple columns is also possible.

• df_sorted2 = df.sort_values(["Region", "Amount"])


PROGRAMMING WITH PYTHON
Data Frame


PROGRAMMING WITH PYTHON
Data Frame

• Create derived columns using arithmetic.

• Example: A new column "Tax" is created as 10 percent of Amount.

• df["Tax"] = df["Amount"] * 0.10

• A "TotalWithTax" column is created.

• df["TotalWithTax"] = df["Amount"] + df["Tax"]


PROGRAMMING WITH PYTHON
Data Frame

• Creating Derived Columns


PROGRAMMING WITH PYTHON
Data Frame

• Creating Derived Columns


PROGRAMMING WITH PYTHON
Data Frame

• Profile columns with value_counts and describe.

• A categorical column is analyzed.

• Example: df["Region"].value_counts()

• A numeric column is summarized.

• Example: df["Amount"].describe()

• The information is read to understand range, median and spread.


PROGRAMMING WITH PYTHON
Data Frame

• Profile columns with value_counts and describe


PROGRAMMING WITH PYTHON
Data Frame

• Grouping and Aggregating

• Group by a single categorical column

• Example: Sales are grouped by "Region".

• grp_region = [Link]("Region")

• The total Amount per region is computed.

• sales_by_region = grp_region["Amount"].sum()
PROGRAMMING WITH PYTHON
Data Frame

• View the group names

• grp_region.[Link]()

• View the row indexes belonging to each group

• grp_region.groups

• View one specific group

• grp_region.get_group("south")
PROGRAMMING WITH PYTHON
Data Frame
PROGRAMMING WITH PYTHON
Data Frame


PROGRAMMING WITH PYTHON
Data Frame


PROGRAMMING WITH PYTHON
Data Frame

• Compute multiple aggregates for one column.

• Example: Both mean and sum of Amount per Region are computed.

• region_summary = grp_region["Amount"].agg(["sum", "mean",

"count"])
PROGRAMMING WITH PYTHON
Data Frame

• Compute multiple aggregates for one column.


PROGRAMMING WITH PYTHON
Data Frame

• Group by multiple columns

• Example: Grouping by "Region" and "Product" together is done.

• grp_rp = [Link](["Region", "Product"])


PROGRAMMING WITH PYTHON
Data Frame

• Group by multiple columns


PROGRAMMING WITH PYTHON
Data Frame

• Custom aggregation
PROGRAMMING WITH PYTHON
Data Frame

• Custom aggregation
PROGRAMMING WITH PYTHON
Data Frame

• Reshape grouped data with unstack.

• Example: The Region–Product summary is used.

• rp_table = rp_summary.unstack("Product")

• The result looks like a pivot table with Regions as rows and Products as

columns.

• fillna(0) is applied if missing combinations exist.


PROGRAMMING WITH PYTHON
Data Frame
PROGRAMMING WITH PYTHON
Data Frame

• Combine two data frames


PROGRAMMING WITH PYTHON
Data Frame

• It shows that ProductID is common to both the data frames.

• Uniqueness of ProductID in products is checked with

• products["ProductID"].nunique().

• Count is compared to len(products) to confirm a proper lookup table.


PROGRAMMING WITH PYTHON
Data Frame

• Merge using inner join

• merged_inner = [Link](sales, products, on="ProductID", how="inner")

• It Keep only rows where ProductID exists in both sales and products.

• If a sales row has a ProductID not present in products, it is removed.

• Useful when there is a need for only “valid” or “matched” transactions.


PROGRAMMING WITH PYTHON
Data Frame

• Check number of rows

• print(len(sales), len(merged_inner))

• If merged_inner is smaller, some sales records did not have a matching

ProductID.
PROGRAMMING WITH PYTHON
Data Frame


PROGRAMMING WITH PYTHON
Data Frame


PROGRAMMING WITH PYTHON
Data Frames

• Merge using left join

• merged_left = [Link](sales, products, on="ProductID", how="left")

• Keep every row from sales (left table).

• Add product details wherever ProductID matches.

• If a ProductID is missing in products, those product fields turn into NaN.

• Check number of rows

• print(len(sales), len(merged_left))
PROGRAMMING WITH PYTHON
Data Frames


PROGRAMMING WITH PYTHON
Data Frames

• Load the second sales file

• sales_q2 = pd.read_csv("sales_q2.csv")

• Check that both DataFrames have the same structure

• print([Link])

• print(sales_q2.columns)
PROGRAMMING WITH PYTHON
Data Frames

• Both files must use identical column names and order.

• If anything is different, concatenation will misalign columns.

• Vertically concatenate the two DataFrames

• sales_all = [Link]([sales, sales_q2], ignore_index=True)


PROGRAMMING WITH PYTHON
Data Frames


PROGRAMMING WITH PYTHON
Data Frames


PROGRAMMING WITH PYTHON
Data Frames

• See a combined row count.


PROGRAMMING WITH PYTHON
Data Frames

• Drop unwanted columns


PROGRAMMING WITH PYTHON
DataFrame

• Export the DataFrame

• final_df.to_csv("sales_final.csv", index=False)

• final_df.to_excel("sales_final.xlsx", index=False)
PROGRAMMING WITH PYTHON
Recap

• Pandas

• DataFrame

• Creation

• Storing
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

Sensor Data Handling

Computer Applications
PROGRAMMING WITH PYTHON
Sensor Data

• Sensors detect physical changes and convert them into data the

program can work with.

• Types of sensors

• Temperature sensors track heat levels.

• Light sensors measure brightness.


PROGRAMMING WITH PYTHON
Sensor Data

• Types of sensors

• Motion sensors detect movement.

• Pressure, humidity, sound and gas sensors support more advanced

environments.

• Each sensor produces readings that describe a specific physical quantity.

• These readings are influenced by environment, component quality and placement.


PROGRAMMING WITH PYTHON
Sensor Data - Measurement units and data types

• Every sensor reading carries a unit that makes the number meaningful.

• Temperature uses °C.

• Light uses lux.

• Distance uses centimetres.

• Motion uses true or false.


PROGRAMMING WITH PYTHON
Sensor Data - Measurement units and data types

• The code stores these values using data types that match the information.

• Integer values store whole numbers such as counts from a pulse sensor.

• Float values store continuous measurements such as 25.68 °C.

• Boolean values store states such as HIGH or LOW from a switch or motion

detector.

• Choosing the correct type gives accuracy and avoids incorrect calculations.
PROGRAMMING WITH PYTHON
Sensor Data - Sampling rate and resolution

• Sampling rate shows how often a reading is captured.

• A slow rate gives fewer data points but uses less memory.

• A fast rate captures quick changes.

• A light sensor checking ambient light every 10 milliseconds can track

screen brightness adjustments in real time.


PROGRAMMING WITH PYTHON
Sensor Data - Sampling rate and resolution

• A temperature sensor in a classroom can use one reading every minute.

• Resolution defines the smallest change the sensor can detect.

• A sensor with 0.1 °C resolution detects small temperature shifts.

• A sensor with 1 °C resolution gives coarse data and might hide

important variations.
PROGRAMMING WITH PYTHON
Sensor Data - Noise in readings

• Sensor data includes noise.

• Values fluctuate because of interference, hardware limitations or

environmental changes.

• Noise appears as small variations even when the source stays steady.
PROGRAMMING WITH PYTHON
Sensor Data - Noise in readings

• A stationary temperature probe may show 25.4, 25.5, 25.3 and 25.6

even under stable conditions.

• This variation does not always reflect real change.

• Smoothing, filtering or averaging is used to reduce noise for clearer

analysis.
PROGRAMMING WITH PYTHON
Sensor Data - Analog versus digital signals

• Analog sensors produce continuous values.

• Light intensity or sound levels fall into this type.

• The microcontroller converts the signal into a number using an ADC.

• Digital sensors send discrete values.


PROGRAMMING WITH PYTHON
Sensor Data - Analog versus digital signals

• Motion detectors give 0 or 1.

• Some temperature sensors send digital data packets.

• Analog values give more detail but need conversion.

• Digital values are simple to read and process but provide less fine-

grained information.
PROGRAMMING WITH PYTHON
Sensor Data - Simulation


PROGRAMMING WITH PYTHON
Serial Communication

• Serial communication is used when two devices send data one bit at a time

over a wire.

• Example. A laptop connected to an Arduino board with a USB cable.

• Data flows as a timed stream of bits, not as whole messages at once.

• The key idea is that both sides must agree on how fast bits are sent, how

they are grouped, and which port is used.


PROGRAMMING WITH PYTHON
Serial Communication – Port Name

• A serial port is the connection endpoint that the program talks to.

• The port name tells the operating system which physical or virtual port is used.

• On Windows

• Port names look like COM1, COM2, COM3, COM4

• USB to serial devices are often COM3 or higher

• When an Arduino or similar board is plugged a new COM port appears


PROGRAMMING WITH PYTHON
Serial Communication – Port Name

• On Linux and macOS

• Port names look like /dev/ttyUSB0, /dev/ttyUSB1 for USB to serial

adapters

• Some boards use /dev/ttyACM0, /dev/ttyACM1

• The /dev part is a directory that holds device files


PROGRAMMING WITH PYTHON
Simulate a Virtual Sensor


PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them
PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them
PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them
PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them
PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them

• df['timestamp'] = pd.to_numeric(df['timestamp'], errors='coerce’)

• df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s’)

• df['value'] = pd.to_numeric(df['temp_c'], errors='coerce’)

• df['value_smooth'] = df['value'].rolling(window=5,

min_periods=1).mean()mid_index = len(df) // 2
PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them

• Compute mid index and means for first and second half

• first_half_mean = df['value_smooth'].iloc[:mid_index].mean()

• second_half_mean = df['value_smooth'].iloc[mid_index:].mean()

• If the second half mean is higher, the temperature increased over time.

• If the second half mean is lower, the temperature decreased.

• If both means are close, the environment stayed stable.


PROGRAMMING WITH PYTHON
Visualizing sensor readings and interpreting them


THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

Object Serialization using Pickle

Computer Applications
PROGRAMMING WITH PYTHON
Serialization

• Serialization is the process of converting the object into a format that

can be stored or transmitted.

• After transmitting or storing the serialized data, the object can be

reconstructed later and the exact same structure/object can be

obtained which makes it really convenient to continue using the stored

object later on instead of reconstructing the object from scratch.


PROGRAMMING WITH PYTHON
Serialization

• Object serialization refers to process of converting state of an object

into byte stream.

• Once created, this byte stream can further be stored in a file or

transmitted via sockets etc.

• Reconstructing the object from the byte stream is called deserialization.


PROGRAMMING WITH PYTHON
Serialization

• Python’s terminology for serialization and deserialization is pickling and

unpickling respectively.
PROGRAMMING WITH PYTHON
What can be pickled?

• None, True, and False

• integers, floating point numbers, complex numbers

• strings, bytes, bytearrays

• tuples, lists, sets, and dictionaries containing only picklable objects

• functions defined at the top level of a module (using def, not lambda)

• built-in functions defined at the top level of a module

• classes that are defined at the top level of a module


PROGRAMMING WITH PYTHON
Use cases for Pickle

• Persistence

• Pickle can be used to save Python objects to a file and load them back later.

• This is helpful for storing program state, saving data structures, or caching

objects.

• Interprocess Communication

• Pickle facilitates passing Python objects between different processes or threads

by converting them into a portable byte stream.


PROGRAMMING WITH PYTHON
Use cases for Pickle

• Data Storage

• It's used in databases or other storage systems where Python objects need to

be stored or retrieved without losing their structure.

• Machine Learning and Model Persistence

• In machine learning, Pickle is often used to save trained models or complex data

structures representing models, allowing them to be loaded and used later for

predictions or analysis.
PROGRAMMING WITH PYTHON
Considerations when using Pickle

• Security Risks

• Unpickling data from untrusted sources can lead to security

vulnerabilities.

• Maliciously crafted pickle data can execute arbitrary code when

unpickled, so it's important to only unpickle data from trusted sources.


PROGRAMMING WITH PYTHON
Considerations when using Pickle

• Compatibility

• Pickle is Python-specific.

• While it's efficient for storing and loading Python objects, the serialized

data may not be compatible with other programming languages.


PROGRAMMING WITH PYTHON
Considerations when using Pickle

• Version Dependency

• Pickle data can be affected by changes in Python versions or changes to

the structure of the objects being pickled.

• This can lead to compatibility issues when unpickling objects in a different

environment or Python version.


PROGRAMMING WITH PYTHON
Examples


PROGRAMMING WITH PYTHON
Examples


PROGRAMMING WITH PYTHON
Examples


PROGRAMMING WITH PYTHON
Examples


PROGRAMMING WITH PYTHON
Examples


PROGRAMMING WITH PYTHON
Advantages of using Pickle

• Recursive objects (objects containing references to themselves)

• Pickle keeps track of the objects it has already serialized, so later

references to the same object won’t be serialized again.


PROGRAMMING WITH PYTHON
Advantages of using Pickle

• Object sharing (references to the same object in different places)

• This is similar to self-referencing objects.

• Pickle stores the object once, and ensures that all other references point

to the master copy.

• Shared objects remain shared, which can be very important for mutable

objects.
PROGRAMMING WITH PYTHON
Advantages of using Pickle

• User-defined classes and their instances

• Pickle can save and restore class instances transparently.

• The class definition must be importable and live in the same module as

when the object was stored.


PROGRAMMING WITH PYTHON
Recap

• Serialization

• What can be pickled?

• Usecases

• Common considerations while using Pickle

• Examples

• Advantages
THANK YOU

Computer Applications
PROGRAMMING WITH PYTHON

Computer Applications
PROGRAMMING WITH PYTHON

Python Modules and Packages

Computer Applications
PROGRAMMING WITH PYTHON
Modules

• If a single Python file is created to perform some tasks, that’s called a

script.

• If a Python file is created to store functions, classes, and other

definitions, that’s called a module.

• A module is a file that contains Python code ending with the .py

extension.
PROGRAMMING WITH PYTHON
Modules

• Modules are simply Python files, nothing more.

• The single file in a small program is a module.

• Two Python files are two modules.

• If there are two files in the same folder, a class from one module can be

loaded for use in the other module.


PROGRAMMING WITH PYTHON
Modules

• Modules are files with “.py” extension containing Python code.

• They help to organize related functions, classes or any code block in the

same file.

• It is considered as a best practice to split the large Python code blocks

into modules containing up to 300–400 lines of code.


PROGRAMMING WITH PYTHON
Reason for Modules

• They allow code organization.

• Example

• Store all functions and data related to math in a module called

[Link].
PROGRAMMING WITH PYTHON
Reason for Modules

• Reuse code more easily.

• Instead of copying the same functions from one project to the next, use

the module instead.

• If the module is packaged properly, it can be shared with others on the

Python package index.


PROGRAMMING WITH PYTHON
Modules

• The import statement is used for importing modules or specific classes or

functions from modules.

• Example

• A module called [Link], which contains a class called Database.

• A second module called [Link] is responsible for product-related

queries.
PROGRAMMING WITH PYTHON
Modules

• [Link] needs to instantiate the Database class from [Link] so

that it can execute queries on the product table in the database.

• There are several variations on the import statement syntax that can be used

to access the class


PROGRAMMING WITH PYTHON
Modules

• This version imports the database module into the products

namespace (the list of names currently accessible in a module or

function), so any class or function in the database module can be

accessed using the database.<something> notation.


PROGRAMMING WITH PYTHON
Modules

• import just the one class needed using the from...import syntax
PROGRAMMING WITH PYTHON
Modules

• If, for some reason, products already has a class called Database, and

don't want the two names to be confused, rename the class when used

inside the products module


PROGRAMMING WITH PYTHON
Modules

• If the database module also contains a Query class, import both

classes.

• Import all classes and functions from the database module


PROGRAMMING WITH PYTHON
Organizing Modules

• A package is a collection of modules in a folder.

• Packages group similar modules in a separate directory.

• They are folders containing related modules and an __init__.py file

which is used for optional package-level initialization.

• The name of the package is the name of the folder.


PROGRAMMING WITH PYTHON
Organizing Modules

• Tell Python that a folder is a package to distinguish it from other folders

in the directory.

• To do this, place a (normally empty) file in the folder named

__init__.py.
PROGRAMMING WITH PYTHON
Organizing Modules

• Retail store management system

• Inventory management: Functions for adding and removing

products.

• Billing: Functions for calculating bills and applying discounts.

• Customer management: Functions to manage customer details.

• Utilities: General-purpose functions like logging and date formatting.


PROGRAMMING WITH PYTHON
Organizing Modules

• To organize the project

• Use modules to separate related functionalities into individual

Python files.

• Group these modules into packages for better organization and

reusability.
PROGRAMMING WITH PYTHON
Organizing Modules


PROGRAMMING WITH PYTHON
Organizing Modules

add_product.py

calculate_bill.py

[Link]
PROGRAMMING WITH PYTHON
Organizing Modules

• [Link]
PROGRAMMING WITH PYTHON
Organizing Modules


PROGRAMMING WITH PYTHON
Organizing Modules

• There are two ways of importing modules

• absolute imports

• relative imports
PROGRAMMING WITH PYTHON
Organizing Modules – Absolute Import

• This method specifies the complete path to the module, function, or class

needed to be imported.

• Example

• It is the most common and clear way to import modules in Python, as it

avoids ambiguity and works regardless of the current working directory.


PROGRAMMING WITH PYTHON
Organizing Modules – Absolute Import

• School management system

• Student Management: Adding, removing, and updating student records.

• Teacher Management: Adding, removing, and updating teacher records.

• Utilities: General-purpose functionality, such as logging and formatting

data.
PROGRAMMING WITH PYTHON
Organizing Modules – Absolute Import


PROGRAMMING WITH PYTHON
Organizing Modules – Absolute Import

add_student.py

add_teacher.py

[Link]
PROGRAMMING WITH PYTHON
Organizing Modules – Absolute Import

Absolute Import
PROGRAMMING WITH PYTHON
Organizing Modules - Absolute Import

• Absolute imports are preferred because they are quite clear and

straightforward.

• It is easy to tell exactly where the imported resource is, just by looking

at the statement.

• Additionally, absolute imports remain valid even if the current location

of the import statement changes.


PROGRAMMING WITH PYTHON
Organizing Modules – Relative Import

• When working with related modules inside a package, it seems kind of

redundant to specify the full path.

• Relative imports are basically a way of saying find a class, function, or

module as it is positioned relative to the current module.

• Example, if working in the products module and there is a need import the

Database class from the database module next to it, use a relative import.
PROGRAMMING WITH PYTHON
Organizing Modules – Relative Import

• Library management system

• Books: Manage adding, removing, and searching books.

• Members: Manage member registrations and renewals.

• Utilities: General-purpose helpers like logging and formatting.


PROGRAMMING WITH PYTHON
Organizing Modules – Relative Import


PROGRAMMING WITH PYTHON
Organizing Modules – Relative Import


PROGRAMMING WITH PYTHON
Organizing Modules – Relative Import


PROGRAMMING WITH PYTHON
Organizing Modules – Relative Import

• Can use more periods to go further up the hierarchy.

• Can also go down one side and back up the other.


PROGRAMMING WITH PYTHON
Organizing Modules – Pros

Absolute Imports Relative Imports



Absolute imports are preferred because They are quite succinct.

they are quite clear and straightforward.

It is easy to tell exactly where the Depending on the current location, they

imported resource is, just by looking at can turn the ridiculously long import

the statement. statement to something as simple


PROGRAMMING WITH PYTHON
Organizing Modules – Pros

Absolute Imports Relative Imports



Additionally, absolute imports remain

valid even if the current location of the

import statement changes.


PROGRAMMING WITH PYTHON
Organizing Modules – Cons

Absolute Imports Relative Imports



Absolute imports can get quite verbose, Relative imports can be messy,
depending on the complexity of the particularly for shared projects where
directory structure. directory structure is likely to change.

Relative imports are also not as readable


as absolute ones, and it’s not easy to tell
the location of the imported resources.
PROGRAMMING WITH PYTHON
Recap

• Modules

• Organizing Modules

• Absolute Imports

• Relative Imports

• Pros and Cons


THANK YOU

Computer Applications

You might also like