Python Notes
Python Notes
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])
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
Simple If Statement
Syntax
if condition:
statement
Example
age = 18
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
Nested If
age = 25
citizen = True
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)
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()
result = add(10,20)
print(result)
Output:
30
print(area(10,5))
Output:
50
Types of Arguments
1. Positional Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable Length Arguments
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
print(factorial(5))
Output:
120
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]
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)
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
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
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
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
print([Link](10,20))
print([Link](5,6))
Output:
30
30
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
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.
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]
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
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
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
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
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
destination = open("[Link]","w")
data = [Link]()
[Link](data)
[Link]()
[Link]()
content = [Link]()
[Link]()
content = [Link]()
words = [Link]()
print("Words =", len(words))
[Link]()
Syntax Error
if True
print("Hello")
Output:
SyntaxError
Runtime Error
print(10/0)
Output:
ZeroDivisionError
Logical Error
length = 10
breadth = 5
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
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")
result = a/b
print(result)
except ValueError:
print("Invalid Number")
except ZeroDivisionError:
print("Division by Zero")
except:
print("Unknown Error")
except Exception as e:
print("Error:",e)
Output:
Error: division by zero
print(a/b)
except ZeroDivisionError:
print("Error")
else:
print("Executed Successfully")
Output:
2.0
Executed Successfully
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
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]
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
print(sqrt(49))
Output:
7.0
print(sqrt(16))
print(pow(2,3))
Output:
4.0
8.0
print([Link])
Output:
3.141592653589793
print([Link])
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
[Link]
def area_square(side):
return side*side
print([Link](10,20))
Output:
30
[Link]
import employee
[Link]("John",50000)
Output:
Name: John
Salary: 50000
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
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
df = pd.read_csv("[Link]")
print([Link]())
14. SCIKIT-LEARN
Introduction
Scikit-learn is one of the most popular machine learning libraries.
Installation
pip install scikit-learn
X = [Link]([[1],[2],[3],[4]])
Y = [Link]([2,4,6,8])
model = LinearRegression()
[Link](X,Y)
print([Link]([[5]]))
Output:
[10.]
model = DecisionTreeClassifier()
Applications:
Disease Prediction
Spam Detection
Student Performance 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]()
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.
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.
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
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
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
def display(self):
print("Person Class")
class Student(Person):
pass
s = Student()
[Link]()
Output:
Person Class
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
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
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.
def fly(self):
print("Bird Flying")
class Sparrow(Bird):
def fly(self):
print("Sparrow Flying")
class Eagle(Bird):
def fly(self):
print("Eagle Flying")
for b in birds:
[Link]()
Output:
Sparrow Flying
Eagle Flying
Operator Polymorphism
print(10 + 20)
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
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
student = {
"name":"John",
"age":21
}
file = open("[Link]","wb")
[Link](student,file)
[Link]()
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
db = [Link]("student")
db["name"] = "John"
db["age"] = 21
[Link]()
Reading Data
import shelve
db = [Link]("student")
print(db["name"])
[Link]()
Output:
John