Python Notes
Python Notes
PYTHON
Table of contents
Chapter 1
Introduction ………………………………………………………………. 03
Chapter 2
Operators
Data Types
(List, Tuple, Dictionary etc.) ………………………………………………………………. 10
Chapter 4
Control statements
Chapter 5
Function
(User define, built-in function etc.) ………………………………………………………………. 40
Chapter 6
Exception Handling
(All types of exception) ………………………………………………………………. 50
Chapter 7
File Handling
2|Page
Introduction
History of python
Python is a high-level, interpreted, and general-purpose programming language that emphasizes code readability and
simplicity. It was created by Guido van Rossum in the late 1980s while he was working at the Centrum Wiskunde &
Informatica (CWI) in the Netherlands. Van Rossum wanted to develop a language that combined the capabilities of the ABC
language with access to system calls and file systems, making it suitable for scripting and automation. He officially released
Python to the public in 1991 as version 0.9.0. The language was named "Python" after the British comedy group Monty
Python, not the snake, reflecting van Rossum's desire to make programming fun. Python quickly gained popularity due to its
clear syntax and dynamic typing, which made it easier to learn and use compared to other programming languages. Over the
years, it has evolved significantly, with major versions such as Python 2.0 (released in 2000) introducing features like garbage
collection and list comprehensions, and Python 3.0 (released in 2008) improving language consistency and Unicode support.
Today, Python is maintained by the Python Software Foundation and is widely used in web development, data science,
machine learning, automation, and many other fields, making it one of the most popular programming languages in the
world.
Python plays a crucial role in shaping the career of [Link] students across various branches, especially in Computer Science,
IT, Electronics, and even Mechanical and Civil engineering. Its simple syntax and readability make it an ideal first programming
language, helping students build a strong foundation in coding. Python is extensively used in data science, machine learning,
artificial intelligence, web development, cyber security, and automation, which are high-demand areas in the current job
market. With libraries like NumPy, Pandas, TensorFlow, and Django, students can develop real-world applications ranging from
data analysis to full-stack web applications. For electronics and robotics students, Python is used with Raspberry Pi and
Arduino to control hardware. In core engineering branches, Python helps in tasks like simulation, data visualization, and
automating repetitive calculations. Python is also widely used in academic projects, internships, and research work due to its
versatility and strong community support. Knowing Python increases job opportunities, aids in cracking technical interviews,
and makes students industry-ready. Additionally, it is a preferred language in competitive coding and hackathons. Thus,
learning Python not only enhances technical skills but also opens up multiple career paths, making it an essential asset in any
[Link] student’s career journey.
Python offers numerous advantages in real-world applications, making it one of the most widely used and preferred
programming languages globally. Its biggest strength lies in its simplicity and readability, which allows both beginners and
professionals to write clean and efficient code quickly. Python is platform-independent, meaning code written in Python can
run on Windows, macOS, or Linux without modification. One of Python’s greatest assets is its vast collection of libraries and
frameworks like NumPy for scientific computing, Pandas for data analysis, Django and Flask for web development, and
TensorFlow and PyTorch for machine learning. These tools reduce development time and effort significantly.
Python is heavily used in data science, artificial intelligence, machine learning, automation, web development, cyber
security, game development, and even robotics. It is also useful in automation scripts, saving businesses time and reducing
errors in repetitive tasks. Due to its widespread industry adoption by companies like Google, NASA, Netflix, and Instagram,
Python skills are highly valued in the job market. Moreover, Python has a massive community that offers continuous support
and development. Whether it's building a quick prototype or managing a large-scale application, Python delivers speed,
flexibility, and scalability—making it ideal for real-world problem-solving across domains.
3|Page
Use Of C: - We Can Develop Any System Program (OS), Compiler, System Driver, Desktop App.
Use Of C++: - Game Development, System Program, Web App, Desktop App.
Version of python
3.14.4
Two versions:
4|Page
❖ In python3 everything is called as class. To represent any class, we make some object. For a class we can create n
numbers of object is used to access number of a class.
Classname object_name;
Objectname = classname ()
• Most widely used language in AI, machine learning, data analysis, and automation.
5|Page
OPERATORS
Expression: - Collection of both operator and operand is called expression.
E.g.: - res = 4 + 6
Operator → =, +
Operand → res,4,6
➢ Using A-Z, a-z, 0-9 but no space and symbol are allowed. One symbol can be allow i.e. _(underscore).
➢ Keyword can’t be used as any variable name.
➢ 1st character must be letter but not digit.
Types of Operators:
Using operation
6|Page
Arithmetic operators
It refers to symbol or functions that perform mathematical operation such as addition, subtraction, multiplication, division
etc. These operators allow for numerical calculations and manipulation within computer programs.
Examples:
Conditional operators:
Syntax:
Examples:
Logical operator
➢ Logical and & or return a expression & logical not return bool value.
➢ In logical and if all condition are true then It is true otherwise false.
➢ In logical or if anyone condition is true then it is true otherwise false.
➢ In logical not it alter the case.
Examples:
Bitwise operator
Res = -n-1
❖ I/P (dec value) → convert dec to bin → operation → bin to dec → O/P (dec).
7|Page
Bits & | ^
00 0 0 0
01 0 1 1
10 0 1 1
11 1 1 0
Examples:
Assignment operator
Examples:
Compound assignment
Example:
Membership operator
If present return true otherwise false but if object is not iterable then raise an error.
Syntax:
8|Page
Examples:
Identity operator
It checks reference value of object. If two object reference are same then it return true otherwise false.
If two object values are same and both object are mutable then it return true otherwise false.
9|Page
PREDEFINE CLASS / DATA TYPES / DATA
STRUCTURE / LITERALS
In python everything is called as class and to represent class we make object.
Function Method
Function is block of code which is called independently by Method is called dependently by its name associated with
its name. an object.
If any data (parameters) are passed, they are passed A method is implicitly passed the object on which it is
explicitly. invoked.
Function does not deal with class and its instance concept Method can operate on the data that is contained by the
corresponding class.
Basic points:
Index:
➢ Arithmetic :
“+“- merge element
“*” – replicate elements
➢ Relational :
“>, <” – only check 1st index and return result.
“>=, <=, ==, !=” – check each element or length of object.
➢ Assignment :
“=” – make a copy.
➢ Membership : in, not in
➢ Identity : is, is not
➢ Slicing: It returns a sublist or group of elements.
Slicing is two types:
• Regular: [start : stop]
• Extended:[start : stop : step]
[Start: stop]→ start from given index number till the previous of given stop index no.
11 | P a g e
OUTPUT
12 | P a g e
Predefine list class function
OUTPUT
13 | P a g e
List class predefine method
Method Description
append(x) Add item x to the end
insert(i, x) Insert item x at position i
extend(iterable) Extend list by appending elements from iterable
remove(x) Remove first occurrence of x
pop([i]) Remove and return item at index i (last if not specified)
index(x[, start[, end]]) Return index of first occurrence of x
count(x) Return number of times x appears
sort() Sort the list in ascending order
reverse() Reverse the list in place
copy() Return a shallow copy of the list
clear() Remove all elements from the list
14 | P a g e
OUTPUT
If we define a list within another list then that is called as nested list.
Basic point:
15 | P a g e
❖ It is a immutable object.
❖ To make tuple element minimum two element or more that 2 elements are required.
❖ Without () we make tuple object if more than one element are separated by comma.
Index: index is use to make read and write but not update operation because it is immutable object.
not in Membership Checks if an element is not in the tuple 4 not in (1, 2, 3) → True
<, <=, >, >= Comparison Compares tuples lexicographically (1, 2) < (2, 1) → True
16 | P a g e
Tuple class predefine function
➢ index () – to get index of given value present in tuple. It always give first occurence.
➢ count() – to count occurrence of given value
bytes() / bytearray()
➢ It is predefining class.
➢ It is iterable
➢ It supports int type value in range (0-255).
➢ To get single element we used index.
But one difference is bytes() is immutable object and bytearray() is mutable object.
Basic points:
17 | P a g e
Index: Set doesn’t support index because it is non-linear data structure.
➢ - : difference
➢ & : intersection
➢ | : union
➢ ^ : symmetric difference
➢ = : copy
➢ in,not in
➢ is, is not
➢ Slicing is not support because it doesn’t support index.
Output
18 | P a g e
Set class predefine function
➢ len()
➢ max()
➢ min()
➢ sum()
➢ sorted()
➢ del()
Output
pop()
Removes and returns a [Link]()
random element
remove(elm)
Removes elm from the set [Link](3)
(raises error if not found)
discard(elm)
Removes elm if it exists [Link](3)
(no error if not found)
clear()
Removes all elements [Link]()
from the set
copy()
Returns a shallow copy of s2 = [Link]()
the set
Adds all elements from
update(other) other into the set (like [Link]({4, 5})
union in-place)
difference(other)
Returns elements in s but [Link](t)
not in other (new set)
Removes elements found
difference_update(other) in other from the set s.difference_update(t)
(modifies in-place)
intersection(other)
Returns a new set with [Link](t)
common elements
19 | P a g e
Method Description Example
Keeps only elements also
intersection_update(other) in other (modifies in- s.intersection_update(t)
place)
symmetric_difference(other)
Returns elements in either s.symmetric_difference(t)
set but not both (new set)
Updates set with
symmetric_difference_update(other) symmetric difference s.symmetric_difference_update(t)
elements
issubset(other)
Returns True if set is [Link](t)
subset of other
issuperset(other)
Returns True if set is [Link](t)
superset of other
isdisjoint(other)
Returns True if sets have [Link](t)
no elements in common
20 | P a g e
Output
Basic points:
Key :
not in Checks if a key does not exist in the dictionary 'age' not in d
22 | P a g e
Dict predefine functions
❖ NOTE: ALL FUNCTIONS ONLY WORK WITH KEY BUT NOT WITH VALUE.
➢ len()
➢ max()
➢ min()
➢ sorted()
➢ del()
➢ sum(): if all key in numeric type.
23 | P a g e
Output:
Predefine methods
update(other_dict)
Updates dictionary with key-value pairs from another dictionary or iterable of [Link]({'a': 1, 'b':
pairs 2})
popitem() Removes and returns the last inserted key-value pair (LIFO order) [Link]()
pop(key[, default])
Removes the specified key and returns the value. If key not found, returns [Link]('a', 'not found')
default if given
keys() Returns a view object of all keys in the dictionary [Link]()
24 | P a g e
Output:
Basic points:
25 | P a g e
String class operator
not in Checks if a substring does not exist in the string 'java' not in 'Python' True
<, <=, >, >= Lexicographically compares strings based on Unicode values 'apple' < 'banana' True
f'' (f-strings) Modern formatting for embedding expressions f"Age: {25}" 'Age: 25'
Output
26 | P a g e
String class predefine function
➢ len()
➢ max()
➢ min()
➢ sorted()
➢ ord() → get char to its ascii value
➢ chr() → get ascii value to char
Method Description
capitalize() Capitalizes the first character of the string.
casefold() Converts string to lowercase, more aggressive than lower().
center(width) Centers the string within the given width, padding with spaces.
count(sub) Counts occurrences of a substring.
encode() Encodes the string into bytes using a specified encoding.
endswith(suffix) Checks if string ends with the specified suffix.
expandtabs(tabsize) Replaces tabs with spaces (default tab size = 8).
find(sub) Returns the lowest index of the substring (or -1 if not found).
format() Formats string using placeholders {}.
format_map(mapping) Similar to format(), but uses a dictionary-like object.
index(sub) Like find(), but raises ValueError if not found.
isalnum() Returns True if all characters are alphanumeric.
isalpha() Returns True if all characters are alphabetic.
isascii() Returns True if all characters are ASCII.
isdecimal() Returns True if all characters are decimal (0–9).
isdigit() Returns True if all characters are digits.
isidentifier() Returns True if string is a valid Python identifier.
islower() Returns True if all cased characters are lowercase.
isnumeric() Returns True if all characters are numeric (includes superscripts, etc.).
isprintable() Returns True if all characters are printable.
isspace() Returns True if all characters are whitespace.
istitle() Returns True if string is title-cased.
27 | P a g e
Method Description
isupper() Returns True if all cased characters are uppercase.
join(iterable) Joins elements of an iterable with the string as a separator.
ljust(width) Left-justifies string in a field of given width.
lower() Converts all characters to lowercase.
lstrip() Removes leading whitespace or specified characters.
maketrans() Returns a translation table (used with translate()).
partition(sep) Splits the string at the first occurrence of sep.
removeprefix(prefix) Removes the specified prefix if present (Python 3.9+).
removesuffix(suffix) Removes the specified suffix if present (Python 3.9+).
replace(old, new) Replaces all occurrences of a substring with another.
rfind(sub) Returns the highest index of the substring (or -1 if not found).
rindex(sub) Like rfind(), but raises ValueError if not found.
rjust(width) Right-justifies string in a field of given width.
rpartition(sep) Splits the string at the last occurrence of sep.
rsplit(sep) Splits string from the right at sep.
rstrip() Removes trailing whitespace or specified characters.
split(sep) Splits string at separator into a list.
splitlines() Splits string at line boundaries (\n, \r\n, etc.).
startswith(prefix) Checks if string starts with the specified prefix.
strip() Removes leading and trailing whitespace or characters.
swapcase() Swaps case (upper <-> lower).
title() Capitalizes first letter of each word.
translate(map) Translates characters using translation table.
upper() Converts all characters to uppercase.
zfill(width) Pads string on the left with zeros to fill width.
28 | P a g e
29 | P a g e
Output
30 | P a g e
31 | P a g e
Control structure and control statements
Control structure
Control statements
➢ Pass
➢ Break
➢ Continue
➢ Break
➢ Continue
➢ Return
End char () :
1. If statement : If only one condition is given and for that condition only true value is given then used if statement.
And else block is not present.
Syntax: -
i. If condition: True/if block logic/expression
ii. If condition:
True block/if block/expression
(if we use multiline expression)
2. If else statement: If only one condition is given and for that condition both True and False value is given then use if
else statement. Else block never check any condition.
32 | P a g e
Syntax: -
if condition:
else:
3. elif statement: if multiple conditions are given and for each condition true is given then used elif statement. Use up
to nth term condition.
Syntax: -
if condition:
True value / expression
elif condition:
else:
False value / expression
4. nested if statement: within if block if we define another if block then that is called as nested if.
Syntax:
if condition1:
# Outer if block
if condition2:
# Inner if block
# Do something
else:
# Do something else
else:
# Do something different
Output
33 | P a g e
OUTPUT
Example
34 | P a g e
OUTPUT:
Example
Output
35 | P a g e
Question
➢ While
➢ For
for, while is called entry loop whereas do while is called as exit control loop.
➢ initialization
➢ Condition
➢ Logic / expression
➢ Update value
While loop
It allow only iterable object. In python while loop supports else block, If condition is false then else block will eexecute.
Examples:
36 | P a g e
Questions
For loop only works with iterable object and return each iter element. But if object is not iterable then it raise an error (object
is not iterable)in python list, tuple, bytes, bytearray, set, str, frozenset are iterable object.
Syntax:
print(iter)
OR
For i in iterable_object:
print(i)
Example
Example
range() class
Example
Control statements
• pass
• break
• continue
exit()
Pass statement: To define empty definition we used pass ststement. To avoid logic / body of any definition we used pass
keyword. Pass is used to avoid the indentation error.
Uses of pass
break is used to terminate current iteration / loop and move the cursor outside of current loop.
Example
38 | P a g e
exit() It is used to terminate a program.
Continue: It is use to skip the current iteration and move the cursor head of loop to start again.
In while loop before continue we must update value but in for update.
Program
39 | P a g e
Function
Function is block of code to solve any given task. def keyword is used to define a function in python.
In c / c++ every program start execution from main() and in java it start execution from main() method. But in python main() is general
function / user define function.
To execute any function both function definition and calling are used. Without definition if we call a function ten it raise an
Error (NameError).But with function definition without call program will be execute but not output and no error.
❖ NOTE: IN PYTHON 1ST WE DEFINE A FUNCTION THEN CALL THAT FUNCTION OTHERWISE ERROR.
Example
Types of variable
➢ Global variable
➢ Local variable
Global variable
If a variable is not belongs to any function then that variable is called as global variable.
If a variable is not define within any function then such types of variables is called as global variable.
40 | P a g e
Local variable
If a variable is belongs to any function then that variable is called as local variable in that function.
If we define any variable within a function then such types of variable are called as local variable.
If local var and global var name is same then function will give priority to local var but not global var.
Local variable can be access where it is local but for other function that will be not accessible.
Parameter / argument
• Actual parameter: - If a parameter is used at the time of function definition then such types of variable is called as
formal parameters.
• Formal parameter: - if a variable is used at the time of function call then such type of variable is called as actual
parameters.
41 | P a g e
❖ NOTE: ACTUAL PARAMETER CAN’T BE CHANGE BUT FORMAL PARAMETER NAME MAY BE SAME AS ACTUAL
PARAMETER OR DIFFERENT.
❖ NOTE: NUMBER OF PARAMETER PASS IN CALLING TIMES AND CATCH IN DEFINITION TIME MUST BE SAME.
Example
Example
Example
Nested function
If a function is define with in another function then such type of function is called as nested function.
Nested function can be access all attribute where it is nested but modification / update is not allow.
If we try to update then it raise an error(unboundedLocalError). To avoid that error we use nonlocal keyword.
Example
42 | P a g e
First class object : (without class)
If we pass a function definition as actual argument then that concept is called as first class object and that function name is
first class object.
Example
Call by value (not supported by python): - Any modification / update in formal parameter can’t be update with atual
parameter. Because both actual and formal parameter allocates different memory.
Call by address (not supported by python): - Any modification / update in formal parameter can be update with atual
parameter. Because both actual and formal parameter allocates single memory.
Call by reference: - reference type doesn’t allocate memory, it use which memory allocate previously.
➢ In python all immutable object works like reference as value type int, float, complex, None, bytes, string, frozenset
are immutable object in python.
➢ In python all mutable object work like reference as reference type list, bytearray, set, range, dictionary are mutable
object in python.
43 | P a g e
Example (reference as reference type)
Return statement
Return statement return a value to caller function (from where call function).
Example
Example
In c, c++ return statement by default return only one value , but In python we can be return multiple value using pack and
unpack.
44 | P a g e
Function overloading
Multiple functions having same name with different signature (number of parameters of types of parameter) is called as
function overloading.
Lambda function
If a function has no name then that function is called as anonymous function. So lambda function is called as anonymous
function.
Example
Predefine function
map() function
Example
Example
45 | P a g e
filter() function
filter function works with each element of iterable object and return only true value according to given condition.
Example
reduce() function
reduce function works with each element of iterable object and return only int type of object. Reduce function present in
functools module so before works with reduce function we must import sys module return type is int type.
Example
Example
generator() function
without return statement if we want return a sequence / list of element we used generator function.
The return type of generator function is generator object. From that generator object to set single element we used next()
within a function in place of return . if we used yield function
46 | P a g e
Recursion function
If we solve any task in recursion that can be solve using loop and vice versa.
Maximum recursion is raise an error (Recursionerror) . Loop is better than recursion because loop doesn’t allocate memory
where as each recursion allocate memory inside stack management.
To set recursion limit we used sys module. Inside sys module setrecursionlimit() attribute is used to set value.
Example
Types of arguments
Positional as argument
At the time of function definition which arguments are used is called as positional / required positional as arguments.
Numbers of argument pass and catch must be same otherwise it raise an error.
If we change the order of arguments then program will be execute but we get invalid input.
Keyword as argument
Number of argument pass and catch must be same otherwise it raise an error.
But if we change the order of arguments then also we get valid output due to keyword as argument.
47 | P a g e
If we take both positional and keyword as argument then 1st we write all positional argument then write keyword as
argument otherwise we get SyntaxError.
Default as argument
Number of argument pass and catch may be same or not, if same then which argument is pass that argument is catch
otherwise at time of definition which argument value we set that value will be execute.
If user passes n number of arguments to catch all argument with one parameter we used variable length as argument.
At the time of program execution if we initialised any object / argument that is called as comment line argument .
Which we pass at the time of execution that must be store in argv(argument evctor). All argument must be string type.
48 | P a g e
Example
Example
49 | P a g e
Exception handling
In programming Error are two types:
Before execution if we get some error or then that error is called as SyntaxError.
SyntaxError doesn’t allow to start execution process. At the time of compilation it raise an Error.
E. g: - IndentationError, TabError
Runtime Error
It allow to start the execution process but doesn’t stop the execution process normally. It stop abnormally then that process is
called as runtime error. Each runtime error is called as exception. Invalid input is responsible.
It is an alternate way to achieve / complete the given task. To complete / achieve the task we used some terms: try, except,
else, finally.
• Predefine exception
• User define exception
But for all predefine exception are derived from parent exception class.
risk code/logic/input
except:
alternet key
else:
success code
finally:
final message
50 | P a g e
Types
Example
We can define a custom exception by creating a new class from the derived built in exception parent class. To define user
define Exception we used raise keyword.
Syntax:
Pass
try:
------
except CustomException:
-------
Example
51 | P a g e
File handling
Each program allocates memory inside RAM segment when process will start but at the end of process which memory
allocate that memory is also deallocate.
To store any data we used variable. Inside variable if we store any data that can’t be reused, to reused that data we store that
data in secondary storage device permanently.
➢ Text file: which file can be read and write by user. E.g.: pdf, xls, ppt,all programming files
➢ Binary file: Which file can’t be read and write by user but understand by user is called binary file. E.g.: video, audio
• Read
• Write
• Update (read & write)
Before any operation we must open a file and after operation we must close that file.
[Link] ()
Types of mode:
'a' Append mode. Creates a file if it doesn't exist; writes at the end.
'w+' Write and read. Overwrites file if it exists, creates new otherwise.
52 | P a g e
✅ Binary File Modes (Add 'b' to any of the above)
Mode Description
Example
53 | P a g e
Example
Example
How to get file pointer position and how to set file pointer position
Example
54 | P a g e
Binary file operation
• using notepad
• using excel
But by using programming language we make csv file or to work with csv file we used csv modules.
Example
55 | P a g e
Zip file
56 | P a g e
advance Python
Table of contents
Chapter 1
Chapter 2
57 | P a g e
Module and Package
Module
Any program save by using .py is called as module. Inside module who will present is known as attribute of that module.
Attribute can be any variable, any constant, any function or class.
By using module we can access one program attribute on another program. When we work with module it create link
between different program to module (_pyche_).
Inside module only we can define any variable, function, method or class. But not access these attributes.
• Built-in module
• User-define module
• External module
Package
Multiple modules present in a single folder is called as package and inside package also we can write sub package.
❖ NOTE: MODULENAME AND PROGRAM AND PACKAGE NAME SHOULD NOT BE SAME.
Syntax: (how to get import module / how to access attribute using module)
Import modulename
[Link]
[Link] ()
attribute1
newname1
Attributename
58 | P a g e
User-define module
Creation of module
Built-in module
In python built-in module are modules that are automatically installed and available as part of the python standard library.
You can use them without needing to install any external packages. They are written in c for performance and provide
standard functionality, such as file handling, math operation, system functions, and more.
Module Purpose
math Mathematical operation
sys Access to system-specific parameters
os Interact with the operating system
datetime Work with dates and times
random Generate random numbers
json Handle JSON data
re Regular expression
time Time-related function
Example
59 | P a g e
External module
An external module is a module or package that is not included In the python standard library. These must be installed
separately. Usually using a tool like pip.
Module Purpose
numpy Numerical computations and arrays.
pandas Data analysis and manipulation
matplotlib Data visualization(plots,graphs etc.)
requests Send HTTP requestes(API communication)
flask Web development framework
django High-level web framework
pygame Game development
Opencv-python Image and video processing
Example
60 | P a g e
Oops(object oriented programming system)
Object-Oriented Programming (OOP) is a method of programming where software is designed using classes and
objects. It helps in organizing code by grouping related data and behaviour.
Class: In python everything is an object. So to make or create any object we make some plans or blueprint or model is
nothing called as class.
class classname:
‘’’doc string’’’
pass
class classname:
‘’’doc string’’’
Attribute list
Behaviour list
doc means document string. It describe details about the class. It is a optional but better use.
Example
61 | P a g e
Object Object is nothing is variable of class type .
Class allocates one time memory whereas objects allocate n times memory.
Example
62 | P a g e
Example
Encapsulation means bundling data and methods that operate on that data within one unit (i.e., class) and restricting access
to some components.
Example
Benefits:
• Improves security
Abstraction means showing only essential details and hiding the internal implementation.
Benefits:
63 | P a g e
Inheritance – “Reusability”
Inheritance allows a class (child) to inherit properties and methods from another class (parent).
Types:
• Single Inheritance
• Multilevel Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
➔ Single Inheritance: One child class inherits from one parent class
➔ Multilevel Inheritance: One class inherits from another child class, forming a chain
➔ Multiple Inheritance: One class inherits from more than one parent class
64 | P a g e
➔ Hierarchical Inheritance: Multiple child classes inherit from a single parent class
Polymorphism means the same function/method behaves differently for different classes or objects.
Types:
• Compile-time Polymorphism (Method Overloading) – Not directly supported in Python but simulated. Compile-time
polymorphism allows multiple methods in the same class to have the same name but different number or type of
parameters.
• Run-time Polymorphism (Method Overriding) – Supported using inheritance. If the child class has a method with the
same name and parameters as in the parent class, the child's method overrides the parent's method.
65 | P a g e
Example (Method Overriding):
Constructor: – __init__()
Destructor: – __del__()
self
cls
Types of Methods:
66 | P a g e
Real-Life Analogy Summary
Advantages of OOPS :
1. Modularity
• Each class handles its own logic, making the program cleaner and easier to manage.
2. Code Reusability
• Inheritance allows new classes to reuse methods and attributes from existing classes, reducing repetition.
4. Real-World Mapping
• Classes and objects represent real-world entities, making the code more intuitive and easier to understand.
5. Polymorphism
67 | P a g e
“Learning never exhausts the mind.”
Stay curious. Stay consistent. Keep building amazing things with Python!
You
68 | P a g e