Python Programming
Python Programming
I - SEMESTER
UNIT-I
INTRODUCTION TO PYTHON
Introduction to Python:
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
Web development (server-side),
Software development,
Mathematics,
System scripting.
Features of Python:
1. Simple
Python is a simple and minimalistic language. Reading a good Python
program feelsalmost like reading English language.
2. Easy to learn
Python uses very few keywords. Python has an extraordinarily simple syntax
and simple program structure.
3. Open Source
There is no need to pay for Python software. Python is FLOSS (Free/Library
and Open Source Software). Its source can be read, modified and used in
programs as desired by the programmers.
4. High level language
When you write programs in Python, you never need to bother about the low-
level details such as managing the memory used by your program, etc.
5. Dynamically typed
Python provides IntelliSense. IntelliSense to make writing your code easier
and more error-free. IntelliSense option includes statement completion, which
provides quick access to valid member function or variables, including global,
via the member list. Selecting from the list inserts the member into your code.
6. Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make
it work on) many platforms. All your Python programs can work on any of
these platforms without requiring any changes at all if you are careful enough
to avoid any system-dependent features.
7. Platform independent
When a Python program is compiled using a Python compiler, it generates
byte code. Python’s byte code represents a fixed set of instructions that run on
all operating systems and hardware. Using a Python Virtual Machine
(PVM), anybody can run these byte code instructions on any computer
system. Hence, Python programs are not dependent on any specific operating
system.
8. Procedure and Object Oriented
Python supports procedure-oriented programming as well as object-oriented
programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In
object- oriented languages, the program is built around objects which combine
data and functionality.
FLAVORS OF PYTHON
Flavors of Python simply refers to the different Python compilers. These
flavors are useful to integrate various programming languages into Python. Let
us look at some of these flavors:
i. C Python
C Python is the Python compiler implemented in C programming language. In
this, Python code is internally converted into the byte code using standard C
functions. Additionally, it is possible to run and execute programs written in
C/C++ using CPython compiler.
ii. J Python
Earlier known as J Python. Jython is an implementation of the Python
programming language designed to run on the Java platform. Jython is
extremely useful because it provides the productivity features of a mature
scripting language while running on a JVM.
iii. PyPy
This is the implementation using Python language. PyPy often runs faster than
C Python because PyPy is a just-in-time compiler while CPython is an
interpreter.
iv. Iron Python
Iron Python is an open-source implementation of the Python programming
language which is tightly integrated with the .NET Framework.
v. Ruby Python
Ruby Python is a bridge between the Ruby and Python interpreters. It embeds
a Python interpreter in the Ruby application’s process using FFI (Foreign
Function Interface).
vi. Python xy
Python(x,y) is a free scientific and engineering development software for
numerical computations, data analysis and data visualization based on Python.
vii. Stockless Python
Stack less Python is a Python programming language interpreter. In practice,
Stack less Python uses the C stack, but the stack is cleared between function
calls
viii. Anaconda Python
Anaconda is a free and open-source distribution of the Python and R
programming languages for scientific computing, that aims to simplify
package management and deployment. Package versions are managed by the
package management system conda.
MEMORY
MANAGEMENT IN PYTHON
Garbage Collector
Garbage Collection is how the memory is freed when not use and how it
can be made available for other objects. Python deletes the objects that are no
longer in use. This is what we call Garbage Collection. The garbage collector
initiates its execution with the program and is activated if the reference count
drops to zero.
Static Memory Allocation – Stack
In static memory allocation, the memory is allocated at the compile time.
The Stack data structure stores the static memory.
Static int x=2;
Dynamic Memory Allocation – Heap
In dynamic memory allocation, the memory is allocated at the run time.
The Heap stores the dynamic memory. It frees up the memory space if the object
is no longer needed.
x = [0]*2
As we discussed above, the garbage collector initiates its execution with
the program and is activated if the reference count drops to zero.
Reference Count
The Python garbage collector initiates its execution with the program and
is activated if the reference count drops to zero. Let us see when the reference
count increase or decreases.
numpy.
The array index should be positive integer. Array index can be positive and
negative integer. Negative index
represents location from the end of the
array.
Indentation of statements in not necessary Indentation is required to represents a
blockof statements.
A semicolon is used to terminate the New line indicates end of the statements
and semicolon is used as an expression
Statements and comma is used to
separator.
separateexpressions / variables.
It supports in-line assignment It does not supports in-line assignment.
location
from the end of the array.
Indentation of statements in not necessary Indentation is required to represents a
blockof statements.
A semicolon is used to terminate the New line indicates end of the statements
statements and comma is used to and semicolon is used as an expression
separate separator.
expressions / variables.
The collection objects like stack, linked The collection objects like lists and
list orvector but not primitive data types dictionariescan store objects of
like int, any type including
float, char etc., numbers and lists.
None data type: The none data type represents an object that does not contain
any value. In java language it is called “NULL” object. But in Python it is called
as “none”. In Python maximum of only one ‘none’object is provided. If no
value is passed to the function, then the default value will be taken as ‘none’.
SEQUENCES
A sequence represents a group of items or elements. There are six types of
sequences in Python. Important sequences as follows,
str
list
tuple
str data type : The str represents string data type. A string is a collection of
character enclosed in single or double quotes. Both are valid.
E.g. str=”kvn” # str is name of string variable
str=’vedish’ # str is name of string variable
Triple double quote or triple single quotes are used to embed a string in a another
string (Nested string).
str=”””This is ‘str data type’ example”””
print(str) # output is : This is ‘str data type’
example
The [] operator used to retrieve specified character from the string. Thestring
index starts from 0. Hence, str[0] indicates the 0th character in the string.
e.g str=” SSCASC Tumkur”
print(str) # it display - SSCASC Tumkur
print(str[0]) # it display - G
OPERATORS
Operators are special symbols which represents computation. They are
applied on operand(s), which can be values or variables.
Same operator can behave differentlyon different data types. Operators
when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and
Assignment. Value and variables when used with operator are known as
operands.
1. Arithmetic Operators:
Symbol Description Example-1 Example-2
+ Addition >>> 5 + 6 >>>’SSCASCT’+’B
CA’
11
SSCASCTBCA
- Subtraction >>>10-5 >>>5 – 6
5 -1
* Multiplication >>> 5*630 >>>’SSCASCT’ * 2
SSCASCTSSCASCT
/ Division >>> 10 / 5 >>>5 /2.0
2 2.5
% Remainder / Modulo >>> 5 % 2 >>>15%5
1 0
** Exponentiation >>> 2**38 >>>2**8256
// Integer Division >>> 7.0 // 2 >>>3//21
3.0
2. Relational Operators:
3. Logical Operators:
Symbol Description Example-2
or If any one of the operand is true, then >>> 7<=10 or 7 ==10
condition becomes TRUE
True
and If both the operands are true, then the >>>7<10 and 7 >20
condition becomes TRUE
False
4. Assignment Operator:
Symbol Description Example-1
= Assigned values from right side >>> x=10
operands
to left variable. 10
the left operand
Bitwise Operator: a bit is the smallest unit of data storage and it can have only
one of the two values, 0 and 1. Bitwise operators works on bits and perform bit-
by-bit operation.
Membership operators
Python has membership operators, which test for membership in a
sequence, such as strings, lists or tuples. There are two membership operators are:
Symbol Description Example
in Returns True if the specified operand is found>>> x = [1,2,4,6,8]
in the sequence
>>> 3 in x false
Not in Returns True if the specified operand is found>>> x = [1,2,4,6,8]
in the sequence
>>> 3 not in x true
UNIT-II
INPUT AND OUTPUT:
CONTROL STATEMENTS
If Statements
One-way if statement executes the statements if the condition is
true. The syntax for a one-way if statement is:
if boolean-expression:
Statement # Note that the statement(s) must be indented
The reserved word if begins a if statement.
The condition is a Boolean expression that determines whether or
not the body will beexecuted. A colon (:) must follow the
condition.
The block is a block of one or more statements to be executed if
the condition is true.
The statements within the block must all be indented the same
number of spaces from the left. The block within an Example: To
demonstrate simple if
#Get two integers from the user
Dividend = int(input('Please enter the number to divide: '))
Divisor = int(input('Please enter dividend: ')) # If possible, divide them and report
the resultif divisor != 0:
Quotient = dividend/divisor
Print(dividend, '/', divisor, "=", quotient)print('Program finished')
Output
Please enter the number to divide: 4Please enter dividend: 5
4 / 5 = 0.8
Program finished
>>>
If-else statements
A two-way if-else statement decides which statements to execute based
on whether the condition is true or false.
The syntax for a two-way if-else statement:
if boolean-expression:
Statement(s) #for-the-true-case ,the statement(s) must be indented
Else: statement(s) #for-the-false-case
Example: to demonstrate if else
Percent=float(input("enter percentage"))if percent >= 90.0:
Print ("congratulations, you got an a") print ("you are doing well in this class")
Else:
Print ("you did not get an a")
Print ("see you in class next week")
Nested if statements.
A series of tests can written using nested if statements.
Example: Nestedif percent=float(input("Enter Percentage")) if (percent >=
90.00):
Print ('congratuations, you got an A')else:
If (percent >= 80.0): print ('you got a B')
Else:
If (percent >= 70.0): print ('you got a C')
Else:
Print ('your grade is less than a C')
If_elif_else Statement
In Python we can define a series of conditionals (multiple
alternatives) using if for the first one, elif for the rest, up until the final
(optional) else for anything not caught by the other conditionals.
Using else if instead of elif will trigger a syntax error and is not
allowed.
Loops
It is one of the most basic functions in programming; loops are
an important in every programming language. Loops enable is to
execute a statement repeatedly which are referred to as iterations. (A
loop is used to tell a program to execute statements repeatedly).
The simplest type of loop is a while loop.
The syntax for the while loop is:
while loop-continuation-condition:# Loop body
Statement(s)# Note that the statement(s) must be indented
i = initialValue # Initialize loop-control
variable
while i <
endValue: #
Loop body
...
as follows:
for i in range(initialValue, endValue):
# Loop body # Note that the statement(s) must be indented
In general, the syntax of a for loop is:
for var in sequence:# Loop body
The function range(a, b) returns the sequence of integers a, a + 1, ...,
b-2, and b- 1. The range function has two more versions. You can
also use range(a) or range(a, b, k). range(a) is the same as range(0,
a). k is used as step value in range(a, b, k). The first number in the
sequence is a. Each successive number in the sequence will increase
by the step value k. b is the limit. The last number in the sequence
must be less than b.
Break and Continue in Loops
break statement:
When a break statement executes inside a loop, control flow comes out of
the loop immediately:
Example:to demonstrate break
i=0
while i < 7:
print(i) if i == 4:
print("Breaking from loop")
break
i += 1
The loop conditional will not be evaluated after the break
statement is executed. Note that break statements are only allowed
inside loops. A break statement inside a function cannot be used to
terminate loops that called that function.
Executing the following prints every digit until number 4 when
the break statement is met and the loop stops:
Output
01234
ARRAYS
An array is a data structure that stores values of same data type.
In Python, this is the main difference between arrays and lists.
While python lists can contain values corresponding to different
data types, arrays in python can only contain values corresponding to
same data type.
To use arrays in python language, you need to import the standard
array module. This is because array is not a fundamental data type like
strings, integer etc. Here is how you can import array module in
python:
#output: 3
Note in that second example that only one index was returned, even
though the value exists twice in the array
Reverse a python array using reverse() method
The reverse() method reverses the array. my_array = array('i', [1,2,3,4,5])
my_array.reverse()
# array('i', [5, 4, 3, 2, 1])
Sort a python array using sort() method
from array import * my_array = [1,20,13,4,5] my_array.sort() print(my_array)
#output:1,4,5,13,20
Multi-Dimensional Array
An array containing more than one row and column is called
multidimensional array. It is also called combination of several 1D
arrays.2D array is also considered as matrix.
A=array([1,2,3,4])# create 1D array with 1 row B=array([1,2,3,4],[5,6,7,8])
create 2D array with 2 row
Example:2D_array
from numpy import* a=array([[1,2,3],[4,5,6],[7,8,9]])
print(a)#Prints 2D array as rows print("2D Array Element wise Printing")for i in
range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=' ')#Prints array element wiseprint(end='\n')
print(end='\n' )
#2D array As matrix by using matrix funprint("Matrix printing")
a=matrix('1 2 3; 4 5 6 ; 7 8 9')print(a)
Output
[[1 2 3]
[4 5 6]
[7 8 9]]
2D Array Element wise Printing1 2 3
456
789
Matrix printing[[1 2 3]
[4 5 6]
[7 8 9]]
>>>
Matrix in Numpy
In python we can show matrices as 2D array. In numpy, a matrix is
considered as specialized 2D array. It has lot of built in operators on 2D
matrices. In numpy, matrix is created using the following syntax.
Matrix_name=matrix(2D array or string)
Eg. a=matrix('1 2 3;4 5 6;7 8 8')
Matrix addition, multiplication and division.
We can use arithmetic operators like +, -,* ,/ to perform different
operations on matrices.
Example: Matrix_Operation
from numpy import* a=matrix('4 4 4;4 4 4;4 4 4')
b=matrix('2 2 2;2 2 2;2 2 2')print("Printing A matrix") print(a)
print("Printing B matrix")print(b)
print("Printing Addition of two matrix")c=a+b #matrix addition
print(c)
print("Printing Multplication of two matrix")c=a*b #matrix addition
print(c)
print("Printing Division of two matrix")c=a/b #matrix addition
print(c)
Output
Printing A matrix[[4 4 4]
[4 4 4]
[4 4 4]]
Printing B matrix[[2 2 2]
[2 2 2]
[2 2 2]]
Printing Addition of two matrix
[[6 6 6]
[6 6 6]
[6 6 6]]
Printing Multplication of two matrix[[24 24 24]
[24 24 24]
[24 24 24]]
Printing Division of two matrix[[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
>>>
Enter rows,col: 2 2
Enter matrix elements:1 2 3 4The original matrix
[[1 2]
[3 4]]
Printing Transpose of matrix[[1 3]
[2 4]]
>>>
UNIT-III
STRING AND CHARACTERS
Slicing String
Python slicing is about obtaining a sub-string from the given string by
slicing it respectively from start to end.
How String slicing in Python works
For understanding slicing we will use different methods, here we will
cover 2 methods of string slicing, the one is using the in-build slice() method
and another using the [:] array slice. String slicing in Python is about obtaining
a sub-string from the given string by slicing it respectively from start to end.
Python slicing can be done in two ways:
Using a slice() method
Using array slicing [ : : ] method
Index tracker for positive and negative index
String indexing and slicing in python. Here, the Negative comes into
consideration when tracking the string in reverse.
Syntax:
slice(stop)
slice(start, stop, step)
Parameters: start: Starting index where the slicing of object
starts. stop: Ending index where the slicing of object stops. step: It is an
optional argument that determines the increment between each index for
slicing. Return Type: Returns a sliced object containing elements in the given
range only.
Example:
Output:
String slicing
AST
SR
GITA
For example,
larger = max(3, 4)
Calls max(3, 4) and assigns the result of the function to the variable
larger.
Another example of a call that is treated as a value is
print(max(3, 4))
This prints the return value of the function call max (3, 4).
RECURSION
A recursive function is one that invokes itself. Or A recursive
function is a function that calls itself in its definition.
For example the mathematical function, factorial, defined by factorial
(n) = n*(n-1)* (n-2)*...*3*2*1. can be programmed as
def factorial(n):
#n here should be an integer
if n == 0:return 1 else:
return n*factorial(n-1)
Any recursive function can be divided into two parts.
First, there must be one or more base cases, to solve the simplest
case, which is referred to as the base case or the stopping condition
Next, recursive cases, here function is called with different
arguments, which are referred to as a recursive call. These are values that
Python Tuples
A collection of ordered and immutable objects is known as a tuple. Tuples
and lists are similar as they both are sequences. Though, tuples and lists are
different because we cannot modify tuples, although we can modify lists after
creating them, and also because we use parentheses to create tuples while we use
square brackets to create lists.
Placing different values separated by commas and enclosed in parentheses forms
a tuple. For instance,
Example
1. tuple_1 = ("Python", "tuples", "immutable", "object")
2. tuple_2 = (23, 42, 12, 53, 64)
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not mandated to build tuples. Tuple packing is the term for this.
Tuple Operations
Like string, tuple objects are also a sequence. Hence, the operators used with
strings are also available for the tuple.
Operator Example
The + operator returns a tuple containing all the >>> t1=(1,2,3)
elements of the first and the second tuple object. >>> t2=(4,5,6)
>>> t1+t2
(1, 2, 3, 4, 5, 6)
>>> t2+(7,)
(4, 5, 6, 7)
The * operator Concatenates multiple copies of >>> t1=(1,2,3)
the same tuple. >>> t1*4
(1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given >>>
t1=(1,2,3,4,5,6)
index. A negative index counts the position from
>>> t1[3]
the right side.
4
>>> t1[-2]
5
Operator Example
The [:] operator returns the items in the range >>>
t1=(1,2,3,4,5,6)
specified by two index operands separated
>>> t1[1:3]
by the : symbol. If the first operand is omitted,
(2, 3)
the range starts from zero. If the second
>>> t1[3:]
operand is omitted, the range goes up to
(4, 5, 6)
the end of the tuple.
>>> t1[:3]
(1, 2, 3)
The in operator returns true if an item exists in the given tuple. >>>
t1=(1,2,3,4,5,6)
>>> 5 in t1
True
>>> 10 in t1
False
The not in operator returns true if an item does not exist in the >>>
given tuple. t1=(1,2,3,4,5,6)
>>> 4 not in t1
False
>>> 10 not in t1
True
UNIT-IV
DICTIONARIES:
Method Description
Page 35 of 53
Popitem()
If key is in the dictionary, return its value. If not,
insert key with a value of d and
return d (defaults to None).
Setdefault(key[,d])
Update the dictionary with the key/value pairsfrom
other, overwriting existing keys.
Update([other])
Values() Return a new view of the dictionary's values
Copy() Return a shallow copy of the dictionary.
Page 36 of 53
Popitem()
Example:
Page 37 of 53
for key in d:
print("key:", key, "Value:", d[key])
# Driver's code
D = {'a':1, 'b':2, 'c':3}
func(D)
Output:
key: b Value: 2
key: a Value: 1
key: c Value: 3
Page 38 of 53
def main():
# passing dictionary key-value
# pair as arguments
display(fname ="John",
mname ="F.",
lname ="Kennedy")
# Driver's code
main()
Output:
John F. Kennedy
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions
when it encounters errors. When writing a program, we, more often than not,
willencounter errors. Error caused by not following the proper structure (syntax)
of the languageis called syntax error or parsing error
Zero Division Error:
Zero Division Error in Python indicates that the second argument used in
a division (or modulo) operation was zero.
Overflow Error:
Overflow Error in Python indicates that an arithmetic operation has
exceeded the limits of the current Python runtime. This is typically due to
excessively large float values, as integer values that are too big will opt to raise
memory errors instead.
Import Error:
It is raised when you try to import a module which does not exist. This may
happen if you made a typing mistake in the module name or the module doesn't
exist in its standard path. In the example below, a module named
"non_existing_module" is being imported but it doesn't exist, hence an import
error exception is raised.
Index Error:
Page 39 of 53
An Index Error exception is raised when you refer a sequence which is out
of range. In the example below, the list abc contains only 3 entries, but the
4th index is being accessed,which will result an Index Error exception.
Type Error:
When two unrelated type of objects are combined, Type Error exception is
raised. In example below, an int and a string is added, which will result in Type
Error exception.
Indentation Error:
Unexpected indent. As mentioned in the "expected an indented block"
section, Python not only insists on indentation, it insists on consistent indentation.
You are free to choose the number of spaces of indentation to use, but you then
need to stick with it.
Syntax errors:
These are the most basic type of error. They arise when the Python parser
is unable to understand a line of code. Syntax errors are almost always fatal, i.e.
there is almost never a way to successfully execute a piece of code containing
syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying,
but runs into trouble when following your instructions.
Key Error:
Python raises a KeyError whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary.
Value Error:
In Python, a value is the information that is stored within a certain object.
To encounter a ValueError in Python means that is a problem with the content of
the object you tried to assign the value to.
Python has many built-in exceptions
Which forces your program to output an error when something in it goes
wrong. In Python, users can define such exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception
class.
Different types of exceptions:
Array Index Out Of Bound Exception.
Page 40 of 53
Page 41 of 53
Page 42 of 53
Page 43 of 53
A Python program to unzip the contents of the files that are available in a
zip file
#to view contents of zipped files
from zipfile import *
#Open the zip file
z = ZipFile('test.zip', 'r')
#extract all the file names which are in the zip file
z.extractall()
Page 44 of 53
UNIT-V
CONSTRUCTOR
Page 45 of 53
student.show()
Output:
This is parametrized constructor
Hello John
INHERITANCE
Types of Inheritance in Python Programming
Types of inheritance: There are five types of inheritance in python programming:
Single inheritance
Multiple inheritances
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
i. Single inheritance
When child class is derived from only one parent class. This is called single
inheritance. The example we did above is the best example for single
inheritance in python programming.
ii. Multiple Inheritance
When child class is derived or inherited from more than one parent class. This
is called multiple inheritance. In multiple inheritance, we have two parent
classes/base classes and one child class that inherits both parent classes
properties.
iii. Multilevel Inheritance:
In multilevel inheritance, we have one parent class and child class that is
derived or inherited from that parent class. We have a grand-child class that
is derived from the child class. See the below-given flow diagram to
understand more clearly.
iv. Hierarchical inheritance
When we derive or inherit more than one child class from one(same) parent
class. Then this type of inheritance is called hierarchical inheritance.
v. Hybrid Inheritance
Page 46 of 53
Hybrid inheritance satisfies more than one form of inheritance ie. It may be
consists of all types of inheritance that we have done above. It is not wrong
if we say Hybrid Inheritance is the combinations of simple, multiple,
multilevel and hierarchical inheritance. This type of inheritance is very
helpful if we want to use concepts of inheritance without any limitations
according to our requirements.
POLYMORPHISM
DUCK TYPING PHILOSOPHY OF PYTHON
Duck Typing is a type system used in dynamic languages. For example, Python,
Perl, Ruby, PHP, Javascript, etc. where the type or the class of an object is less
important than the method it defines. Using Duck Typing, we do not check types
at all. Instead, we check for the presence of a given method or attribute.
The name Duck Typing comes from the phrase:
“If it looks like a duck and quacks like a duck, it’s a duck”
Example:
# Python program to demonstrate
# duck typing
class Specialstring:
def __len__(self):
return 21
# Driver's code
if __name__ == "__main__":
string = Specialstring()
print(len(string))
Output:
In this case, we call method len() gives the return value
from __len__ method. Here __len__ method defines the property of the
class Special string The object’s type itself is not significant in this we do not
declare the argument in method prototypes. This means that compilers can not
do type-checking. Therefore, what really matters is if the object has particular
attributes at run time. Duck typing is hence implemented by dynamic languages.
Page 47 of 53
But now some of the static languages like Haskell also supports it. But, Java/C#
doesn’t have this ability yet.
Example: Now, lets look demonstrates how an object be used in any other
circumstances until it is not supported.
Output:
fly with wings
fly with fuel
Traceback (most recent call last):
File "/home/854855e5570b9ce4a9e984209b6a1c21.py", line 20, in
obj.fly()
AttributeError: 'Fish' object has no attribute 'fly'
In this example, we can see a class supports some method we can modify it or
give them new functionality. Duck-typing emphasis what the object can really
do, rather than what the object is.
Page 48 of 53
OPERATOR OVERLOADING
Operators work for user-defined types.
For example, the + operator will perform arithmetic addition on two numbers,
merge two lists, or concatenate two strings.
This feature in Python that allows the same operator to have different meaning
according to the context is called operator overloading.
obj1 = Complex(1, 2)
obj2 = Complex(3, 4)
obj3 = obj1 + obj2
print(obj3)
# Output: (4, 6)
In the above example, we have used the + operator to add
two Complex objects a and b together.
Page 49 of 53
The __add__() method overloads the + operator to add the real and imaginary
parts of the two complex numbers together and returns a new Complex object
with the resulting values.
The __str__() method returns a string representation of the complex number in
the form a + bj.
p1 = Person("Alice", 20)
p2 = Person("Bob", 30)
True
False
Page 50 of 53
Here, __lt__() overloads the < operator to compare the age attribute of two
objects.
The __lt__() method returns,
True - if the first object's age is less than the second object's age
False - if the first object's age is greater than the second object's age We
can define similar methods to overload the other comparison operators. For
example, __gt__() to overload > operator, __eq__() to
overload == operator and so on.
Function Description
Page 51 of 53
METHOD OVERRIDING
Method Overriding in Python is an OOPs concept closely related
to inheritance. When a child class method overrides (or, provides it's own
implementation) the parent class method of the same name, parameters and return
type, it is known as method overriding.
In this case, the child class's method is called the overriding method and
the parent class's method is called the overridden method.
Method overriding is completely different from the concept of method
overloading. Method overloading occurs when there are two functions with the
same name but different parameters. And, method overloading is not directly
supported in Python.
Parent class: The class being inherited is called the Parent or Superclass.
Child class: The class that inherits the properties and methods of the parent class
is called the Child or Subclass.
Key features of Method Overriding in Python
These are some of the key features and advantages of method overriding in
Python --
Method Overriding is derived from the concept of object oriented
programming
Method Overriding allows us to change the implementation of a function
in the child class which is defined in the parent class.
Method Overriding is a part of the inheritance mechanism
Method Overriding avoids duplication of code
Page 52 of 53
Page 53 of 53