0% found this document useful (0 votes)
2 views84 pages

Python Notes

The document provides a comprehensive overview of Python fundamentals, including its features, applications, and basic programming concepts such as variables, data types, operators, control structures, and functions. It also covers data structures like lists, tuples, sets, strings, and dictionaries, alongside modules and packages for modular programming. The content is structured into units, each focusing on specific aspects of Python programming to facilitate learning for students.

Uploaded by

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

Python Notes

The document provides a comprehensive overview of Python fundamentals, including its features, applications, and basic programming concepts such as variables, data types, operators, control structures, and functions. It also covers data structures like lists, tuples, sets, strings, and dictionaries, alongside modules and packages for modular programming. The content is structured into units, each focusing on specific aspects of Python programming to facilitate learning for students.

Uploaded by

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

UNIT I: PYTHON FUNDAMENTALS, CONTROL STRUCTURES AND FUNCTIONS

1. INTRODUCTION TO PYTHON
What is Python?
Python is a high-level, interpreted, object-oriented, and general-purpose programming
language developed by Guido van Rossum in 1991. Python emphasizes code readability and
simplicity, making it one of the most popular programming languages in academia, research,
data science, artificial intelligence, machine learning, web development, and automation.
Features of Python
1. Simple and Easy to Learn
o Uses English-like syntax.
o Easy for beginners.
2. Interpreted Language
o No need for compilation.
o Code is executed line by line.
3. Platform Independent
o Runs on Windows, Linux, macOS, etc.
4. Object-Oriented
o Supports classes and objects.
5. Open Source
o Freely available for use and modification.
6. Extensive Libraries
o Supports AI, ML, Data Science, Web Development, etc.
7. Dynamic Typing
o Variable types are determined automatically.
Applications of Python
 Artificial Intelligence
 Machine Learning
 Data Science
 Web Development
 Scientific Computing
 Automation and Scripting
 Cyber Security
 Internet of Things (IoT)
2. PYTHON INTERPRETER
What is an Interpreter?
An interpreter is software that reads, translates, and executes source code line by line.
Working of Python Interpreter
Python Source Code

Python Interpreter

Byte Code

Python Virtual Machine (PVM)

Output
Advantages
 Easier debugging
 Platform independent
 Interactive execution
Example
print("Welcome to Python")
Output:
Welcome to Python

3. INTERACTIVE MODE
Interactive mode allows users to execute Python statements directly.
Starting Interactive Mode
>>>
Examples
>>> 5+10
15

>>> 20*3
60
>>> print("MCA")
MCA
Advantages
 Immediate results
 Quick testing
 Learning environment
Limitations
 Programs are not saved automatically.
 Not suitable for large projects.

4. VARIABLES
Definition
A variable is a named memory location used to store data.
Syntax
variable_name = value
Example
x = 100
name = "Python"
percentage = 95.5
Memory Representation
x ----> 100
name ---> "Python"
percentage ---> 95.5
Multiple Assignment
a = b = c = 10

print(a)
print(b)
print(c)
Output:
10
10
10
Multiple Variable Assignment
x, y, z = 10, 20, 30

5. IDENTIFIERS
Definition
Identifiers are names used to identify variables, functions, classes, modules, etc.
Rules
1. Must start with a letter or underscore.
2. Cannot begin with a digit.
3. No special symbols except underscore.
4. Keywords cannot be used.
5. Case sensitive.
Valid Identifiers
student
student_name
totalMarks
_age
roll1
Invalid Identifiers
1student
student-name
class
for
6. KEYWORDS
Keywords are reserved words having predefined meanings.
Examples
if
else
while
for
break
continue
return
True
False
None
Displaying Keywords
import keyword
print([Link])

7. VALUES AND DATA TYPES


Definition
Every piece of data stored in Python has a specific type.
Major Data Types
Integer
x = 100
Float
y = 15.75
String
name = "Python"
Boolean
flag = True
Complex
z = 3+4j
Example
a = 10
b = 12.5
c = "MCA"
d = True

print(type(a))
print(type(b))
print(type(c))
print(type(d))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

8. OPERATORS
Operators perform operations on operands.

Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
// Floor Division
** Exponentiation
Example
a = 10
b=3

print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a//b)
print(a**b)

Assignment Operators
Operator Example
= x=10
+= x+=5
-= x-=5
*= x*=5
/= x/=5
Example:
x = 10
x += 5
print(x)
Output:
15

Relational Operators
Operator Meaning
== Equal
!= Not Equal
> Greater Than
< Less Than
>= Greater Than or Equal
<= Less Than or Equal
Example:
a = 20
b = 10

print(a>b)
Output:
True

Logical Operators
Operator Meaning
and Logical AND
Operator Meaning
or Logical OR
not Logical NOT
Example:
x = True
y = False

print(x and y)
print(x or y)
print(not x)

Bitwise Operators
Operator Meaning
& AND
| OR
^ XOR
~ NOT
<< Left Shift
>> Right Shift
Example:
a=5
b=3

print(a & b)
Output:
1

9. BOOLEAN VALUES
Boolean values represent truth.
Boolean Constants
True
False
Examples
print(10 > 5)
print(10 < 5)
Output:
True
False
Boolean Conversion
bool(0)
bool(1)
bool("")
bool("Python")
Results:
False
True
False
True

10. OPERATOR PRECEDENCE


Operator precedence determines execution order.
Highest to Lowest
1. Parentheses ()
2. Exponentiation **
3. Unary +,-
4. *, /, //, %
5. +,-
6. Relational Operators
7. Logical NOT
8. Logical AND
9. Logical OR
Example
x=5+2*3
print(x)
Output:
11
11. EXPRESSIONS
Definition
An expression is a combination of variables, constants, and operators producing a value.
Types
Arithmetic Expression
a+b
Relational Expression
a>b
Logical Expression
(a>b) and (b<c)

12. CONDITIONAL STATEMENTS


Conditional statements enable decision making.

Simple If Statement
Syntax
if condition:
statement
Example
age = 18

if age >= 18:


print("Eligible")

If-Else Statement
Syntax
if condition:
statements
else:
statements
Example
num = 8

if num%2==0:
print("Even")
else:
print("Odd")

If-Elif-Else Ladder
Example
marks = 85

if marks >= 90:


print("A Grade")
elif marks >= 75:
print("B Grade")
elif marks >= 50:
print("C Grade")
else:
print("Fail")

Nested If
age = 25
citizen = True

if age >= 18:


if citizen:
print("Eligible to Vote")

13. LOOPS
Loops execute statements repeatedly.

WHILE LOOP
Syntax
while condition:
statements
Flow
Initialization

Condition
↓ ↓
True False
↓ ↓
Body Exit

Update

Condition
Example
i=1

while i <= 5:
print(i)
i += 1

FOR LOOP
Syntax
for variable in sequence:
statements
Example
for i in range(1,6):
print(i)

Iterating Through String


for ch in "PYTHON":
print(ch)
Output:
P
Y
T
H
O
N

14. BREAK STATEMENT


Used to terminate a loop immediately.
Example
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4

15. CONTINUE STATEMENT


Skips the current iteration.
Example
for i in range(6):
if i == 3:
continue
print(i)
Output:
0
1
2
4
5

16. FUNCTIONS
Definition
A function is a block of reusable code designed to perform a specific task.
Advantages
 Code reuse
 Modularity
 Easier maintenance
 Reduced complexity

Function Definition
def function_name():
statements
Example
def welcome():
print("Welcome MCA Students")

welcome()

17. FUNCTION CALL AND RETURN VALUES


Example
def add(a,b):
return a+b

result = add(10,20)
print(result)
Output:
30

18. PARAMETER PASSING


Parameters receive values from function calls.
Example
def area(length,width):
return length*width

print(area(10,5))
Output:
50
Types of Arguments
1. Positional Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable Length Arguments

19. LOCAL AND GLOBAL SCOPE


Local Variable
Declared inside a function.
def test():
x = 10
print(x)

test()

Global Variable
Declared outside functions.
x = 100

def show():
print(x)

show()

Global Keyword
count = 0

def increment():
global count
count += 1

increment()
print(count)
Output:
1

20. RECURSIVE FUNCTIONS


Definition
A recursive function calls itself until a base condition is reached.
Components
1. Base Case
2. Recursive Case

Factorial Using Recursion


Mathematical Formula:
n !=n(n−1)! , 0 !=1
Program:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)

print(factorial(5))
Output:
120

Fibonacci Series Using Recursion


def fib(n):
if n <= 1:
return n
return fib(n-1)+fib(n-2)

for i in range(10):
print(fib(i), end=" ")
Output:
0 1 1 2 3 5 8 13 21 34
UNIT II – DATA TYPES IN PYTHON, MODULES, PACKAGES AND STANDARD
LIBRARIES
Detailed Notes for MCA Students

UNIT OVERVIEW
Python provides several built-in data structures that allow programmers to store, organize,
and manipulate data efficiently. These data structures include Lists, Tuples, Sets, Strings, and
Dictionaries. Python also supports modular programming through Modules and Packages,
enabling code reuse and easier maintenance.
Learning Objectives
After studying this unit, students will be able to:
1. Understand Python data structures.
2. Create and manipulate Lists, Tuples, Sets, Strings, and Dictionaries.
3. Understand Modules and Packages.
4. Create user-defined modules.
5. Utilize Python Standard Libraries effectively.
6. Develop modular and reusable Python programs.

1. LISTS
Introduction
A List is an ordered collection of elements. Lists are mutable, meaning their contents can be
modified after creation.
Characteristics of Lists
 Ordered collection
 Mutable
 Allows duplicate values
 Can store different data types
 Indexed collection
Syntax
list_name = [element1, element2, element3]
Example
students = ["John", "David", "Mary"]

print(students)
Output
['John', 'David', 'Mary']

Creating Lists
Empty List
mylist = []
List with Different Data Types
data = [10, 20.5, "Python", True]
print(data)
Output:
[10, 20.5, 'Python', True]

List Indexing
Python uses zero-based indexing.
languages = ["Python", "Java", "C++", "PHP"]

print(languages[0])
print(languages[2])
Output:
Python
C++

Negative Indexing
print(languages[-1])
Output:
PHP

List Slicing
Syntax
list[start:stop:step]
Example
numbers = [10,20,30,40,50]

print(numbers[1:4])
Output:
[20, 30, 40]

List Operations
Concatenation
list1 = [1,2]
list2 = [3,4]

print(list1 + list2)
Output:
[1,2,3,4]
Repetition
print([1,2] * 3)
Output:
[1,2,1,2,1,2]

List Methods
append()
Adds an element at the end.
fruits = ["Apple","Mango"]
[Link]("Orange")

print(fruits)
Output:
['Apple', 'Mango', 'Orange']

insert()
[Link](1,"Banana")
Output:
['Apple', 'Banana', 'Mango', 'Orange']

remove()
[Link]("Banana")

pop()
[Link]()

sort()
numbers = [40,10,30,20]
[Link]()

print(numbers)
Output:
[10,20,30,40]

reverse()
[Link]()

Traversing Lists
numbers = [10,20,30,40]

for item in numbers:


print(item)

Nested Lists
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]

print(matrix[1][2])
Output:
6

List Comprehension
A concise way of creating lists.
Syntax
[expression for item in iterable]
Example
squares = [x*x for x in range(1,6)]

print(squares)
Output:
[1,4,9,16,25]

2. TUPLES
Introduction
A Tuple is an ordered collection similar to a list, but it is immutable.
Characteristics
 Ordered
 Immutable
 Allows duplicates
 Faster than lists
Syntax
tuple_name = (elements)
Example
colors = ("Red","Green","Blue")

print(colors)

Accessing Tuple Elements


print(colors[0])
Output:
Red
Tuple Operations
Concatenation
t1 = (1,2)
t2 = (3,4)

print(t1+t2)
Output:
(1,2,3,4)

Repetition
print(t1*3)
Output:
(1,2,1,2,1,2)

Tuple Methods
count()
numbers = (10,20,10,30)

print([Link](10))
Output:
2

index()
print([Link](20))
Output:
1

Advantages of Tuples
 Faster execution
 Data safety
 Lower memory consumption
3. SETS
Introduction
A Set is an unordered collection of unique elements.
Characteristics
 Unordered
 Mutable
 No duplicate elements
 No indexing
Syntax
set_name = {elements}
Example
numbers = {1,2,3,4}

print(numbers)

Duplicate Removal
data = {1,2,2,3,4,4}

print(data)
Output:
{1,2,3,4}

Set Methods
add()
[Link](5)

remove()
[Link](2)

discard()
[Link](10)

Set Operations
Union
A = {1,2,3}
B = {3,4,5}

print(A | B)
Output:
{1,2,3,4,5}

Intersection
print(A & B)
Output:
{3}

Difference
print(A - B)
Output:
{1,2}

Symmetric Difference
print(A ^ B)
Output:
{1,2,4,5}

4. STRINGS
Introduction
A String is a sequence of Unicode characters enclosed in quotes.
Creating Strings
name = "Python"
course = 'MCA'

Accessing Characters
print(name[0])
Output:
P

String Slicing
print(name[1:4])
Output:
yth

String Operations
Concatenation
print("Hello" + " World")
Output:
Hello World

Repetition
print("Hi"*3)
Output:
HiHiHi

String Methods
upper()
text = "python"
print([Link]())
Output:
PYTHON

lower()
print([Link]())

capitalize()
print([Link]())
Output:
Python
replace()
text = "I like Java"

print([Link]("Java","Python"))
Output:
I like Python

split()
sentence = "Python is easy"

print([Link]())
Output:
['Python','is','easy']

join()
words = ["Python","Programming"]

print(" ".join(words))
Output:
Python Programming

String Formatting
Using format()
name = "John"
age = 22

print("Name: {} Age: {}".format(name,age))

Using f-string
print(f"Name:{name} Age:{age}")

5. DICTIONARIES
Introduction
Dictionary stores data in key-value pairs.
Characteristics
 Mutable
 Keys must be unique
 Fast data retrieval
Syntax
student = {
"name":"John",
"age":22,
"course":"MCA"
}

Accessing Values
print(student["name"])
Output:
John

Adding Elements
student["city"] = "Chennai"

Updating Elements
student["age"] = 23

Removing Elements
del student["city"]

Dictionary Methods
keys()
print([Link]())

values()
print([Link]())
items()
print([Link]())

Traversing Dictionary
for key,value in [Link]():
print(key,value)

Nested Dictionary
students = {
"101":{"name":"John","age":21},
"102":{"name":"Mary","age":22}
}

print(students["101"]["name"])
Output:
John

6. MODULES
Introduction
A Module is a file containing Python functions, variables, and classes that can be reused in
other programs.
Advantages
 Code Reusability
 Modularity
 Easy Maintenance

Importing Modules
Example
import math

print([Link](25))
Output:
5.0
Import Specific Function
from math import sqrt

print(sqrt(36))
Output:
6.0

Alias
import math as m

print([Link])
Output:
3.141592653589793

7. MODULE LOADING AND EXECUTION


When Python executes:
import math
the following steps occur:
Import Statement

Search Module

Load Module

Compile (if needed)

Execute Module

Available in Program
Module Search Path
Python searches in:
1. Current Directory
2. PYTHONPATH
3. Standard Library Directories
import sys

print([Link])

8. PACKAGES
Introduction
A Package is a collection of related modules organized in directories.
Structure
College/

├── [Link]
├── [Link]
├── [Link]
└── __init__.py

Importing Package
from College import Student

Advantages
 Better organization
 Namespace management
 Large project development

9. MAKING YOUR OWN MODULE


Step 1: Create Module
File: [Link]
def add(a,b):
return a+b

def sub(a,b):
return a-b
def mul(a,b):
return a*b

def div(a,b):
return a/b

Step 2: Use Module


File: [Link]
import calculator

print([Link](10,20))
print([Link](5,6))
Output:
30
30

10. THE PYTHON STANDARD LIBRARIES


Introduction
The Python Standard Library is a collection of pre-built modules included with Python.
Benefits
 Ready-made functionality
 Reduces development time
 Reliable and optimized

Common Standard Library Modules


Module Purpose
math Mathematical functions
random Random number generation
datetime Date and time
os Operating system functions
sys System-specific functions
statistics Statistical calculations
Module Purpose
collections Advanced data structures
json JSON processing
re Regular expressions
csv CSV file handling

math Module
import math

print([Link](64))
print([Link](5))
print([Link])
Output:
8.0
120
3.141592653589793

random Module
import random

print([Link](1,100))

datetime Module
from datetime import datetime

now = [Link]()

print(now)

os Module
import os

print([Link]())
sys Module
import sys

print([Link])

statistics Module
import statistics

data = [10,20,30,40,50]

print([Link](data))
Output:
30

COMPARISON OF PYTHON DATA TYPES


Feature List Tuple Set Dictionary
Ordered Yes Yes No Yes
Mutable Yes No Yes Yes
Duplicate Values Yes Yes No Keys No
Indexing Yes Yes No Keys Used
Syntax [] () {} {key:value}
UNIT III – FILE HANDLING AND EXCEPTION HANDLING
Detailed Notes for MCA Students

UNIT OVERVIEW
In any programming language, data generated during program execution is stored in memory
temporarily. Once the program terminates, the data is lost. To store data permanently, files are
used. Python provides extensive support for file handling operations such as creating,
opening, reading, writing, updating, and deleting files.
Exception handling is another important feature of Python that helps programmers manage
runtime errors gracefully without abruptly terminating the program.
Learning Objectives
After studying this unit, students will be able to:
1. Understand file concepts and file operations.
2. Open, read, write, and close files.
3. Manipulate file positions.
4. Understand runtime errors and exceptions.
5. Implement exception handling mechanisms.
6. Handle multiple exceptions.
7. Define cleanup actions using finally.

PART A: FILE HANDLING


1. INTRODUCTION TO FILES
What is a File?
A file is a collection of related information stored permanently on secondary storage devices
such as hard disks, SSDs, USB drives, etc.
Need for Files
 Permanent storage of data
 Data sharing between programs
 Backup and recovery
 Large data processing
Examples
 Student records
 Employee databases
 Bank transactions
 Research datasets

2. TYPES OF FILES
Python mainly supports two types of files.
Text Files
Store data in human-readable format.
Examples:
[Link]
[Link]
[Link]
Contents:
John
22
MCA

Binary Files
Store data in binary format (0s and 1s).
Examples:
[Link]
video.mp4
audio.mp3
Characteristics:
 Faster processing
 Not human-readable
 Used for multimedia and databases

3. FILE PATH
Definition
A file path specifies the location of a file in the computer system.
Absolute Path
Specifies the complete location.
Example:
C:\Users\Admin\Documents\[Link]

Relative Path
Specifies location relative to current directory.
Example:
[Link]
or
Data/[Link]

Working with Paths


import os

print([Link]())
Output:
Current working directory path

4. OPENING FILES
open() Function
Used to open a file.
Syntax
file_object = open(filename, mode)
Parameters
 filename → Name of file
 mode → Operation mode

5. FILE MODES
Mode Description
r Read
w Write
a Append
x Create
r+ Read and Write
w+ Write and Read
Mode Description

a+ Append and Read


rb Read Binary
wb Write Binary

Read Mode
file = open("[Link]","r")

Write Mode
file = open("[Link]","w")
Creates file if it does not exist.

Append Mode
file = open("[Link]","a")
Adds content at end of file.

6. CLOSING FILES
close() Method
Used to release system resources.
Syntax
[Link]()
Example
file = open("[Link]","r")

print("File Opened")

[Link]()
Output:
File Opened

Why Close Files?


 Prevents memory leaks
 Saves data properly
 Releases system resources

7. WRITING FILES
write() Method
Used to write data into files.
Example
file = open("[Link]","w")

[Link]("John\n")
[Link]("MCA\n")
[Link]("22")

[Link]()
Contents of file:
John
MCA
22

Writing Multiple Lines


writelines()
file = open("[Link]","w")

data = ["Ram\n","Sam\n","Hari\n"]

[Link](data)

[Link]()

8. READING FILES
read()
Reads entire file.
Example
file = open("[Link]","r")

data = [Link]()

print(data)

[Link]()
Output:
John
MCA
22

read(size)
Reads specified characters.
file = open("[Link]","r")

print([Link](5))

[Link]()
Output:
John

readline()
Reads one line.
file = open("[Link]","r")

print([Link]())

[Link]()
Output:
John

readlines()
Reads all lines into a list.
file = open("[Link]","r")

print([Link]())

[Link]()
Output:
['John\n', 'MCA\n', '22']

9. APPENDING FILES
Example
file = open("[Link]","a")

[Link]("\nDindigul")

[Link]()
Updated File:
John
MCA
22
Dindigul

10. WITH STATEMENT


Python provides automatic file closing.
Syntax
with open(filename,mode) as file:
statements
Example
with open("[Link]","r") as file:
print([Link]())
Advantages:
 Automatic closing
 Cleaner code
 Better resource management

11. FILE POSITION


Every file maintains a cursor position.
Example:
PYT H O N
012345

tell()
Returns current cursor position.
Example
file = open("[Link]","r")

print([Link]())

[Link]()
Output:
0

seek()
Moves cursor to specific position.
Syntax
[Link](position)
Example
file = open("[Link]","r")

[Link](3)

print([Link]())

[Link]()
If file contains:
PYTHON
Output:
HON

FILE HANDLING PROGRAMS


Program 1: Copy File Content
source = open("[Link]","r")

destination = open("[Link]","w")

data = [Link]()

[Link](data)

[Link]()
[Link]()

print("File Copied Successfully")

Program 2: Count Characters


file = open("[Link]","r")

content = [Link]()

print("Characters =", len(content))

[Link]()

Program 3: Count Words


file = open("[Link]","r")

content = [Link]()

words = [Link]()
print("Words =", len(words))

[Link]()

PART B: EXCEPTION HANDLING


12. INTRODUCTION TO EXCEPTIONS
What is an Exception?
An exception is an abnormal condition that occurs during program execution and disrupts
normal flow.
Example
print(10/0)
Output:
ZeroDivisionError

13. ERRORS AND EXCEPTIONS


Errors
Mistakes in program that prevent execution.
Types of Errors
1. Syntax Errors
2. Runtime Errors
3. Logical Errors

Syntax Error
if True
print("Hello")
Output:
SyntaxError

Runtime Error
print(10/0)
Output:
ZeroDivisionError
Logical Error
length = 10
breadth = 5

area = length + breadth


Incorrect logic but no error message.

14. EXCEPTION HANDLING


Python uses:
try
except
finally
blocks.

try-except
Syntax
try:
risky code

except:
handling code
Example
try:
num = 10/0

except:
print("Cannot divide by zero")
Output:
Cannot divide by zero

15. SPECIFIC EXCEPTIONS


Example
try:
x = int(input("Enter Number:"))

except ValueError:
print("Invalid Input")

Handling ZeroDivisionError
try:
a = int(input("Enter A:"))
b = int(input("Enter B:"))

print(a/b)

except ZeroDivisionError:
print("Division by Zero Not Allowed")

16. MULTIPLE EXCEPTIONS


A single try block may generate multiple exceptions.
Example
try:
a = int(input("Enter A: "))
b = int(input("Enter B: "))

result = a/b

print(result)

except ValueError:
print("Invalid Number")

except ZeroDivisionError:
print("Division by Zero")
except:
print("Unknown Error")

17. EXCEPTION OBJECT


Example
try:
x = 10/0

except Exception as e:
print("Error:",e)
Output:
Error: division by zero

18. ELSE CLAUSE


Executed when no exception occurs.
Example
try:
a = 10
b=5

print(a/b)

except ZeroDivisionError:
print("Error")

else:
print("Executed Successfully")
Output:
2.0
Executed Successfully

19. DEFINING CLEAN-UP ACTIONS


finally Block
Executed whether exception occurs or not.
Syntax
try:
statements

except:
statements

finally:
cleanup statements

Example
try:
file = open("[Link]","r")

print([Link]())

except FileNotFoundError:
print("File Not Found")

finally:
print("Program Completed")
Output:
Program Completed

Importance of finally
Used for:
 Closing files
 Closing database connections
 Releasing resources
 Network cleanup

20. USER-DEFINED EXCEPTIONS


Raising Exceptions
Syntax
raise ExceptionName
Example
age = int(input("Enter Age:"))

if age < 18:


raise Exception("Not Eligible")

print("Eligible")
Output:
Exception: Not Eligible

COMPREHENSIVE EXAMPLE
try:
file = open("[Link]","r")

number = int([Link]())

result = 100/number

except FileNotFoundError:
print("File Not Found")

except ValueError:
print("Invalid Data")

except ZeroDivisionError:
print("Division by Zero")

finally:
print("Execution Completed")
DIFFERENCE BETWEEN ERRORS AND EXCEPTIONS
Errors Exceptions
Serious problems Recoverable problems
Program terminates Program can continue
Difficult to handle Can be handled
Example: SyntaxError Example: ZeroDivisionError
UNIT IV - MODULES, PACKAGES
Modules - Introduction - Module Loading and Execution - Packages - Making Your
Own Module - The Python Libraries for Data Processing - Data mining and
Visualization.
UNIT OVERVIEW
Large software applications consist of thousands of lines of code. Managing such large
programs becomes difficult if all code is written in a single file. Python solves this problem
through Modules and Packages, which promote code reusability, maintainability, and
organization.
Modern Python applications also rely heavily on powerful libraries for Data Processing,
Data Mining, and Data Visualization. Libraries such as NumPy, Pandas, Matplotlib,
Seaborn, and Scikit-learn have made Python one of the most widely used languages in Data
Science and Artificial Intelligence.

LEARNING OBJECTIVES
After studying this unit, students will be able to:
1. Understand modules and packages.
2. Create and use user-defined modules.
3. Understand module loading and execution.
4. Develop package-based applications.
5. Use Python libraries for data processing.
6. Apply data mining techniques using Python.
7. Create meaningful visualizations from data.

PART A: MODULES
1. INTRODUCTION TO MODULES
What is a Module?
A module is a Python file containing variables, functions, classes, and executable statements
that can be reused in multiple programs.
Definition
A module is simply a file with the extension:
.py
Example:
[Link]

Need for Modules


Problems Without Modules
 Repeated code
 Difficult maintenance
 Large program complexity
 Reduced readability
Advantages of Modules
1. Code Reusability
2. Easy Maintenance
3. Better Organization
4. Reduced Development Time
5. Improved Readability

Example of a Module
[Link]
def add(a,b):
return a+b

def subtract(a,b):
return a-b

def multiply(a,b):
return a*b

def divide(a,b):
return a/b

[Link]
import calculator
print([Link](10,20))
print([Link](5,6))
Output:
30
30

2. IMPORTING MODULES
Import Entire Module
import math

print([Link](25))
Output:
5.0

Import Specific Functions


from math import sqrt

print(sqrt(49))
Output:
7.0

Import Multiple Functions


from math import sqrt,pow

print(sqrt(16))
print(pow(2,3))
Output:
4.0
8.0

Import Using Alias


import math as m

print([Link])
Output:
3.141592653589793

3. MODULE LOADING AND EXECUTION


What Happens During Import?
When Python executes:
import math
the following sequence occurs:
Import Statement

Search Module

Load Module

Compile (if required)

Execute Module

Create Module Object

Ready for Use

Module Search Path


Python searches modules in:
1. Current Directory
2. PYTHONPATH Environment Variable
3. Standard Library Directories
Viewing Search Path
import sys

print([Link])

4. SPECIAL MODULE VARIABLES


name Variable
Every Python module contains a special variable:
__name__
Example
print(__name__)
Output:
__main__

Example
def test():
print("Function Executed")

if __name__ == "__main__":
test()
This ensures code executes only when the file is run directly.

PART B: PACKAGES
5. INTRODUCTION TO PACKAGES
What is a Package?
A package is a collection of related modules organized into directories.
Package Structure
College/

├── [Link]
├── [Link]
├── [Link]
└── __init__.py
Why Packages?
Advantages
 Better organization
 Avoid naming conflicts
 Easy maintenance
 Supports large projects

Package Hierarchy
University

College Package

Modules

Functions

6. CREATING A PACKAGE
Step 1: Create Folder
MyPackage

Step 2: Create Modules


[Link]
def add(a,b):
return a+b

[Link]
def area_square(side):
return side*side

Step 3: Create [Link]


# Empty file

Step 4: Use Package


from MyPackage import arithmetic

print([Link](10,20))
Output:
30

7. MAKING YOUR OWN MODULE


Example: Employee Module
[Link]
def display(name,salary):
print("Name:",name)
print("Salary:",salary)

[Link]
import employee

[Link]("John",50000)
Output:
Name: John
Salary: 50000

PART C: PYTHON LIBRARIES FOR DATA PROCESSING


8. INTRODUCTION TO DATA PROCESSING
What is Data Processing?
Data Processing is the collection and manipulation of data to produce meaningful
information.
Stages
Raw Data

Collection

Cleaning

Transformation

Analysis

Information

9. NUMPY LIBRARY
Introduction
NumPy (Numerical Python) is used for numerical computations and multidimensional arrays.
Installation
pip install numpy

Creating Arrays
import numpy as np

arr = [Link]([10,20,30,40])

print(arr)
Output:
[10 20 30 40]

Array Operations
import numpy as np

a = [Link]([1,2,3])
b = [Link]([4,5,6])

print(a+b)
Output:
[5 7 9]

Statistical Functions
import numpy as np

data = [10,20,30,40]

print([Link](data))
print([Link](data))
print([Link](data))
Output:
25.0
40
10

10. PANDAS LIBRARY


Introduction
Pandas is used for structured data manipulation.
Features
 Data Cleaning
 Data Analysis
 Data Transformation
 Handling Missing Values

Creating Series
import pandas as pd

s = [Link]([10,20,30])

print(s)

Creating DataFrame
import pandas as pd

data = {
'Name':['John','Mary'],
'Age':[21,22]
}

df = [Link](data)

print(df)
Output:
Name Age
0 John 21
1 Mary 22

Reading CSV Files


import pandas as pd

df = pd.read_csv("[Link]")

print([Link]())

11. DATA CLEANING


Handling Missing Values
[Link]()

Filling Missing Values


[Link](0)

Removing Missing Values


[Link]()

PART D: DATA MINING


12. INTRODUCTION TO DATA MINING
Definition
Data Mining is the process of extracting useful patterns, relationships, and knowledge from
large datasets.
Applications
 Healthcare
 Banking
 Marketing
 Education
 Social Media
 Cyber Security

Data Mining Process


Data Collection

Data Cleaning

Data Integration

Data Mining

Pattern Discovery

Decision Making

13. PYTHON LIBRARIES FOR DATA MINING


Library Purpose
Scikit-Learn Machine Learning
NumPy Numerical Analysis
Pandas Data Manipulation
SciPy Scientific Computing
TensorFlow Deep Learning
Keras Neural Networks

14. SCIKIT-LEARN
Introduction
Scikit-learn is one of the most popular machine learning libraries.
Installation
pip install scikit-learn

Example: Linear Regression


from sklearn.linear_model import LinearRegression
import numpy as np

X = [Link]([[1],[2],[3],[4]])
Y = [Link]([2,4,6,8])

model = LinearRegression()

[Link](X,Y)

print([Link]([[5]]))
Output:
[10.]

15. CLASSIFICATION EXAMPLE


from [Link] import DecisionTreeClassifier

model = DecisionTreeClassifier()
Applications:
 Disease Prediction
 Spam Detection
 Student Performance Analysis

PART E: DATA VISUALIZATION


16. INTRODUCTION TO DATA VISUALIZATION
Definition
Data Visualization is the graphical representation of data to understand patterns and trends.
Advantages
 Better understanding
 Easier interpretation
 Decision support
 Trend analysis

Visualization Process
Raw Data

Processing

Analysis

Charts/Graphs

Insights

17. MATPLOTLIB
Introduction
Matplotlib is a popular plotting library.
Installation
pip install matplotlib

Line Chart
import [Link] as plt

x = [1,2,3,4]
y = [10,20,30,40]

[Link](x,y)
[Link]()

Example Visualization
A typical comparison of chart types used in data visualization:
Common data visualization chart usage
Illustrative comparison of frequently used chart types in analytics.
0255075100Bar ChartLine ChartPie ChartScatter Plot

Bar Chart
import [Link] as plt

subjects = ["Python","Java","C++"]
marks = [90,80,85]

[Link](subjects,marks)
[Link]()

Pie Chart
import [Link] as plt

labels = ["Python","Java","C++"]
sizes = [50,30,20]

[Link](sizes,labels=labels)
[Link]()

18. SEABORN
Introduction
Seaborn is built on Matplotlib and provides attractive statistical graphics.
Installation
pip install seaborn

Example
import seaborn as sns
import [Link] as plt

tips = sns.load_dataset("tips")
[Link](data=tips,x="total_bill",y="tip")

[Link]()

19. REAL-WORLD APPLICATIONS


Healthcare
 Disease Prediction
 Medical Image Analysis
 Patient Monitoring
Education
 Student Performance Prediction
 Attendance Analytics
 Learning Behavior Analysis
Banking
 Fraud Detection
 Risk Assessment
 Loan Approval Prediction
Agriculture
 Crop Yield Prediction
 Weather Analytics
Artificial Intelligence
 Machine Learning Models
 Deep Learning Systems
 Computer Vision Applications

COMPARISON OF MODULES AND PACKAGES


Feature Module Package
Definition Single Python File Collection of Modules
Extension .py Directory
Reusability Yes Yes
Organization Limited Better
Complexity Small Programs Large Projects
UNIT V
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around objects rather than functions and logic. An object represents a real-world entity
that contains data (attributes) and behavior (methods).
Python fully supports Object-Oriented Programming and provides powerful features such as
Classes, Objects, Inheritance, Encapsulation, Polymorphism, Class Methods, Static Methods,
and Object Persistence.
OOP helps developers build modular, reusable, maintainable, and scalable software systems.

LEARNING OBJECTIVES
After studying this unit, students will be able to:
1. Understand Object-Oriented Programming concepts.
2. Create classes and objects.
3. Define attributes and methods.
4. Implement inheritance.
5. Apply encapsulation principles.
6. Use polymorphism in Python.
7. Differentiate class methods and static methods.
8. Implement object persistence using files and serialization.

1. INTRODUCTION TO OBJECT ORIENTED PROGRAMMING


What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a methodology that organizes programs using
objects and classes.
Real-Life Example
Consider a Student.
Attributes
 Name
 Roll Number
 Department
 Age
Behaviors
 Study()
 WriteExam()
 AttendClass()
In OOP:
Student

Object

Attributes + Methods

Advantages of OOP
Code Reusability
Existing code can be reused.
Modularity
Programs are divided into smaller modules.
Security
Data can be protected using encapsulation.
Maintainability
Easy to modify and update.
Scalability
Suitable for large applications.

2. CLASS AND OBJECT


Class
A class is a blueprint or template for creating objects.
Definition
A class defines:
 Attributes (Data)
 Methods (Functions)
Syntax
class ClassName:
statements

Object
An object is an instance of a class.
Example
class Student:
pass

s1 = Student()
Here:
Student → Class
s1 → Object

3. CREATING A CLASS
Example 1: Simple Class
class Student:
name = "John"

s1 = Student()

print([Link])
Output:
John

4. CONSTRUCTOR (init)
What is a Constructor?
A constructor initializes object attributes when an object is created.
Syntax
def __init__(self):
statements
Example
class Student:

def __init__(self):
print("Object Created")
s1 = Student()
Output:
Object Created

Constructor with Parameters


class Student:

def __init__(self,name,age):
[Link] = name
[Link] = age

s1 = Student("John",21)

print([Link])
print([Link])
Output:
John
21

5. INSTANCE VARIABLES
Variables belonging to each object.
Example
class Employee:

def __init__(self,name,salary):
[Link] = name
[Link] = salary

e1 = Employee("Ram",50000)

print([Link])
print([Link])
Output:
Ram
50000

6. CLASS METHODS
Definition
A class method operates on the class itself rather than on object instances.
Syntax
@classmethod
def method(cls):
statements

Example
class College:

college_name = "PSNACET"

@classmethod
def display(cls):
print(cls.college_name)

[Link]()
Output:
PSNACET

Why Use Class Methods?


 Access class variables
 Modify class attributes
 Factory methods

7. INSTANCE METHODS
Instance methods work with object data.
Example
class Student:

def __init__(self,name):
[Link] = name

def display(self):
print([Link])

s1 = Student("David")

[Link]()
Output:
David

8. CLASS VARIABLES
Shared among all objects.
Example
class Student:

college = "PSNACET"

def __init__(self,name):
[Link] = name

s1 = Student("John")
s2 = Student("Mary")

print([Link])
print([Link])
Output:
PSNACET
PSNACET
9. CLASS INHERITANCE
Definition
Inheritance allows one class to acquire properties and methods of another class.
Advantages
 Code Reusability
 Reduced Redundancy
 Better Maintainability

Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

10. SINGLE INHERITANCE


Example
class Person:

def display(self):
print("Person Class")

class Student(Person):
pass

s = Student()

[Link]()
Output:
Person Class

11. MULTILEVEL INHERITANCE


class GrandFather:
def show1(self):
print("GrandFather")

class Father(GrandFather):
def show2(self):
print("Father")

class Son(Father):
def show3(self):
print("Son")

s = Son()

s.show1()
s.show2()
s.show3()
Output:
GrandFather
Father
Son

12. MULTIPLE INHERITANCE


class Father:
def father_property(self):
print("Father Property")

class Mother:
def mother_property(self):
print("Mother Property")

class Child(Father,Mother):
pass
c = Child()

c.father_property()
c.mother_property()
Output:
Father Property
Mother Property

13. METHOD OVERRIDING


Definition
Redefining a method in child class.
Example
class Animal:

def sound(self):
print("Animal Sound")

class Dog(Animal):

def sound(self):
print("Bark")

d = Dog()

[Link]()
Output:
Bark

14. ENCAPSULATION
Definition
Encapsulation means wrapping data and methods into a single unit and restricting direct
access.
Benefits
 Data Security
 Controlled Access
 Better Maintenance

Public Members
class Student:

name = "John"
Accessible anywhere.

Protected Members
class Student:

_name = "John"
Conventionally protected.

Private Members
class Student:

__name = "John"
Not directly accessible.

Example
class Bank:

def __init__(self):
self.__balance = 10000

def show(self):
print(self.__balance)

b = Bank()
[Link]()
Output:
10000

15. POLYMORPHISM
Definition
Polymorphism means "many forms".
A single interface can perform different actions.

Method Overriding Example


class Bird:

def fly(self):
print("Bird Flying")

class Sparrow(Bird):

def fly(self):
print("Sparrow Flying")

class Eagle(Bird):

def fly(self):
print("Eagle Flying")

birds = [Sparrow(), Eagle()]

for b in birds:
[Link]()
Output:
Sparrow Flying
Eagle Flying
Operator Polymorphism
print(10 + 20)

print("Python" + " Programming")


Output:
30
Python Programming
The '+' operator behaves differently for numbers and strings.

16. ABSTRACTION
Definition
Abstraction hides implementation details and shows only essential features.
Example
from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod
def area(self):
pass

class Circle(Shape):

def area(self):
return 3.14*5*5

c = Circle()

print([Link]())
Output:
78.5
17. CLASS METHOD VS STATIC METHOD
Static Method
A static method does not access class or instance variables.
Syntax
@staticmethod
def method():
statements

Example
class Calculator:

@staticmethod
def add(a,b):
return a+b

print([Link](10,20))
Output:
30

Comparison: Instance Method vs Class Method vs Static Method


Feature Instance Method Class Method Static Method
Decorator None @classmethod @staticmethod
First Parameter self cls None
Access Instance Variables Yes No No
Access Class Variables Yes Yes No
Object Required Yes No No

Example
class Demo:

company = "ABC"

def instance_method(self):
print("Instance Method")

@classmethod
def class_method(cls):
print([Link])

@staticmethod
def static_method():
print("Static Method")

d = Demo()

d.instance_method()

Demo.class_method()

Demo.static_method()
Output:
Instance Method
ABC
Static Method

18. PYTHON OBJECT PERSISTENCE


Definition
Object Persistence refers to saving objects permanently and retrieving them later.
Why Persistence?
 Store program data
 Save application state
 Database interaction
 Data sharing

19. PICKLE MODULE


Introduction
Python provides the Pickle module for object serialization.
Serialization converts an object into a byte stream.
Import
import pickle

20. SAVING OBJECTS USING PICKLE


Example
import pickle

student = {
"name":"John",
"age":21
}

file = open("[Link]","wb")

[Link](student,file)

[Link]()

21. LOADING OBJECTS USING PICKLE


Example
import pickle

file = open("[Link]","rb")

data = [Link](file)

print(data)

[Link]()
Output:
{'name':'John','age':21}
22. OBJECT SERIALIZATION FLOW
Python Object

[Link]()

Binary File

[Link]()

Python Object

23. SHELVE MODULE


Introduction
The shelve module stores Python objects like a dictionary.
Example
import shelve

db = [Link]("student")

db["name"] = "John"
db["age"] = 21

[Link]()

Reading Data
import shelve

db = [Link]("student")

print(db["name"])

[Link]()
Output:
John

REAL-WORLD APPLICATIONS OF OOP


Banking System
Classes:
 Customer
 Account
 Transaction
Hospital Management
Classes:
 Doctor
 Patient
 Appointment
Library Management
Classes:
 Book
 Member
 Librarian
E-Commerce
Classes:
 Product
 Customer
 Order
Artificial Intelligence
Classes:
 Dataset
 NeuralNetwork
 Model

COMPARISON OF OOP CONCEPTS


Concept Purpose
Class Blueprint
Concept Purpose
Object Instance of Class
Inheritance Reuse Existing Code
Encapsulation Data Protection
Polymorphism One Interface, Many Forms
Abstraction Hide Complexity
Persistence Permanent Storage

You might also like