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

Python Programming

les base de Python

Uploaded by

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

Python Programming

les base de Python

Uploaded by

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

YAOUNDE HIGHER SCHOOL OF ECONOMICS AND MANAGEMENT

B.P.: 12 687 Yaoundé Tél.: (237) 243 26 31 86 / 698 18 25 53 / 652 62 20 96.


E-mail: info@[Link] Site web: [Link]

Arrêté de création No14/0140/MINSUP/SG/DDES du 14 avril 2014


Arrêté d’ouverture No15/0141/MINESUP/SG/DDES du 02 avril 2015

ELITE PROFESSIONAL MASTERS IN INFORMATION SYSTEM MANAGEMENT

SPECIALITY: INFORMATION SYSTEM MANAGEMENT

Course Title: Python Programming

Eng. Ernest MBUMBO

ACADEMIC YEAR : 2024-2025

1
PLANNING DU DEROULEMENT DES ENSEIGNEMENTS

IDENTIFICATION DE L’ENSEIGNANT

Name (s) and surname (s) : [Link] MBUMBO

Lecturer Specialisation : (Masters) Telecommunications/ (B-Tech) CyberSecurity

Phone Number :(+237) 674653215

Email :ernestmbmb@[Link]

COURSE OBJECTIVES

This course will help students to ;

1) Develop problem solving skills using python programming principles

2) Understand python syntax, sematics, and data types

3) Learn how to design, implement, test, and debug software applications

4) Familiarize students with industry-standard programming languages and tools

5) Prepare students for advanced software engineering courses

6) Learn to work with databases, web development, and networking

7) Develop skills in testing and debugging

8) Apply python to various domains (examples data science, AI, Machine learning)

9) Understand testing and validatiion techniques

PEDAGOGIC APPROACH

Teaching methods
 Lecturers and discussions
 Hands-on programming labs
 Group projects and activities
 Online resources and tutorials

EVALUATIONS

Programming assignments and projects =30% Intra semester exam =30% Final Exam=40%

2
 Group projects and presentations
 The lecturer can give a surprise quiz
Soft skills
 Teamwork and collaboration
 Communication and presentation
 Time management and organisation
 Critical thinking and problem solving
 Adaptability and continuous learning

COURSE CONTENT
Chapter1: Variables, data types, and operators

Chapter2: Control Structures(if/else, loops, conditional statements)

Chapter3: Functions and Modules

Chapter4 : lists, tuples, dictionaries, and sets

Chapter5 : Object-oriented programming (classes, objects, inheritance)

Chapter6 : file input/output and persistence

Chapter7 : arrays and link lists

Chapter8 : flask and Django framework for web development

Chapter9 : Numpy and pandas framework for data analysis

Chapter10: Python for networking and sockets

STUDENT ’ASSIGNMENTS

N° Title Type of work (indoor, home, team)

1 a) Declare and print variables : assign a value to a variable Team


and print it.
b) Basic calculations : Use variables to perform basic
arithmetic operations (+,-,/)
c) String manipulation : assign a string to a variable and
perform operations (concatenation, slicing)
d) List operations : create a list, append elements, and
access indices.
e) create a dictionary basic : create a dictionary, access
keys, and values
2 a) Simple if-else statements : determine if a number is Indoor
even or odd.
b) if-elif-else statements : grade student scores
c) For loops : print numbers from 1 to 10
d) While loops : Simulate a countdown timer
e) nested loops : print multiplication tables
3 a) Simple calculator function : write a function to perform Home
basic arithmetic operations
b) Greeting functions : write a function to print personalized
greetings

3
c) Function arguments : understand positional and
keyword arguments
d) Web scraper : write a function to extract data from a
specific site
4 a) Create a list of numbers and perform basic operations Indoor
(indexing, slicing, append, insert, remove)
b) Write a program to find the maximum and minimum
values in a list
c) Sort a list in ascending and descending order
d) Create a dictionary and perform basic operations(key-
value pairs, access, update)
5 a) Create a simple class with attribute and methods Indoor
b) Implement inheritance (single and multiple)
c) Create a class with encapsulation (private attributes)
d) Develop a simple banking system using classes and
objects
e) Create a shape class hierarchy (rectangle, circle, and
triangle)
f) Develop a student management system using classes
and objects
6 a) Write a program for file searching and filtering Team
b) Write a program for file compression and
decompression
c) Implement file encryption and decryption
d) Develop a simple text editor
7 a) Perform basic array operations (insert, delete, search Team
b) Perform array rotation (left, right)
c) Write a program to merge two sorted arrays
d) Find the closest pair of elements in an array
e) implement a circular linked list
8 a) Create a simple ‘’i am learning core programming’’
django app.
b) Build a basic django blog with CRUD operations Home
c) Implement user authentication and authorization
d) Build a django e-commerce website with payment
gateway
e) Create a django forms for user input validation
9 a) Write an array for statistical operations (mean, median, Team
standard deviation)
b) Write a program to perform linear algebra operations
(matrix, multiplication, inverse
c) Write a program for statistical analysis (regression,
correlation)
d) Advanced statistical analysis (hypothesis testing,
confidence intervals)
e) data frame creation and manipulation
10 a) Implement a simple chat application using TCP Indoor
b) Create a simple VPN using Python
c) Implement a simple web server using http
d) Create a scanner that identifies vulnerabilities in web
applications
e) write a python program for advanced persistent threats
detector

4
5
PLANIFICATION DES SEANCES

Session Part Title The Relevant Chapter Skills or aptitudes to be developed Pre-course Reading (specify
the section concerned)
Session1  Variables Variables, data types, and operators Develop the skills to use different List, data types, and operators
 Data Types types of python variables, data types
 Operators and operators to create simple
programs
Session2  If statement Control Structures(if/else, loops, Students will develop the skills to use Conditional statement and loops
 If-else statement conditional statements) python conditional statements and
 If-elif-else statement loops to write and implements a
 Nested if statement program.
 Loops (for loop, while loop, do-while loop)

Session3  Introduction to functions and modules Functions and Modules Develop the skills to use python buid Python functions and moduls
- Build-in functions (len (), print (), range ()) in functions and modules
- User defined functions
- Lambda functions
- Generator functions
 Function components (function name,
parameters(arguments), function body, return
statement xxxxx
 Types of function
- simple function, recursive function, higher order
function
Session4  Introduction lists, tuples, dictionaries, and sets Develop the skills to use lists, tuples, List and tuples
 List dictionaries, and sets
 Tuples,
 Dictionaries
 Sets
Session5  Introdution to object oriented programming in Object-oriented programming Develop the skills to use classes, Python object oriented
python (classes, objects, inheritance) objects and inheritance to write programming
 Classes computer programs
 Objects
 inheritance

6
Session6  inheritacne Case Study of Object Oriented Develop the skills to use file input, File input /output and persistence
 functional requirments Programming output and persistence to program
 Non fuctional requirements apps

Session7  Introduction to arrays and links lists arrays and link lists Develop the skills to use arrays and Types of Arrays and linked lists
 Types of arrays linked lists
 Array operations
 Array methods
 Linked list
 Types of link lists
 Link lists operations
 Link list methods
Session8  Introducton to django framework Django framework for web Develop the skills to install and use Django framework components
 Django architecture development django framework to write computer
 Django components apps.
 Django features
 Django tools
 Django deployment
Session9  Introduction to numpy Numpy framework for data analysis Develop the skills to use numpy and Advanced features Numpy
 Key features pandas for data analysis operations
 Nympy data structure
 Nympy operations
 Numpy functions
Session10  Introduction to pandas Pandas framework for data analysis Students will develop the skills to use Advanced features of pandas
 Pandas features pandas for data analysis
 Pandas data structure pandas operations
 Pandas operations
 Pandas functions

7
8
Chapter 1: Variables, Data Types, & Operators

1.1 variables
A variable is the name given to a memory location. A value-holding Python variable is also known as an
identifier. Since Python is an infer language that is smart enough to determine the type of a variable, we do
not need to specify its type in Python. Variable names must begin with a letter or an underscore, but they can
be a group of both letters and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct variables.
1.1.1 Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the program. The
standards to name an identifier are given underneath.

o The variable's first character must be an underscore or alphabet (_).


o Every one of the characters with the exception of the main person might be a letter set of lower-case(a-
z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in the language.
o Names of identifiers are case-sensitive; for instance, my name, and MyName isn't something very
similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
1.1.2 Declaring Variable and Assigning Values

o Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us to
make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is declared automatically
whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.
1.1.3 Object References
When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared to
many other programming languages, the procedure for dealing with variables is a little different.
Python is the exceptionally object-arranged programming language; Because of this, every data item is a part
of a particular class. Think about the accompanying model.
Print("John")
Output:

John

The Python object makes a integer object and shows it to the control center. We have created a string object
in the print statement above. Make use of the built-in type() function in Python to determine its type.
type("John")
Output:

<class 'str'>

In Python, factors are an symbolic name that is a reference or pointer to an item. The factors are utilized to
indicate objects by that name.

9
Let's understand the following example
a = 50

In the above image, the variable a refers to an integer object.


Suppose we assign the integer value 50 to a new variable b.
a = 50
b=a

Object Identity
Every object created in Python has a unique identifier. Python gives the dependable that no two items will have
a similar identifier. The object identifier is identified using the built-in id() function. consider about the
accompanying model.

1. a = 50
2. b=a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:

140734982691168
140734982691168
2822056960944

We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check returned
the same number. We reassign a to 500; The new object identifier was then mentioned.
Variable Names
The process for declaring the valid variable has already been discussed. Variable names can be any length
can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_). Take a look
at the names of valid variables in the following example.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:

Devansh
20
80.5

Consider the following valid variables name.


1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"

10
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
Output:

ABCDEDEFGFI

We have declared a few valid variable names in the preceding example, such as name, _name_, and so on.
However, this is not recommended because it may cause confusion when we attempt to read code. To make
the code easier to read, the name of the variable ought to be descriptive.
The multi-word keywords can be created by the following method.

o Camel Case - In the camel case, each word or abbreviation in the middle of begins with a capital
letter. There is no intervention of whitespace. For example - nameOfStudent, valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For example -
NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement, is a feature
of Python.
We can apply different tasks in two ways, either by relegating a solitary worth to various factors or doling out
numerous qualities to different factors. Take a look at the following example.
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:

50
50
50

2. Assigning multiple values to multiple variables:


Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:

5
10
15

11
The values will be assigned in the order in which variables appear.

1.2 Python Data Types


Every value has a datatype, and variables can hold values. Python is a powerfully composed language;
consequently, we don't have to characterize the sort of variable while announcing it. The interpreter binds the
value implicitly to its type.
a=5
We did not specify the type of the variable a, which has the value five from an integer. The Python interpreter
will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in Python returns
the type of the passed variable. Consider the following illustration when defining and verifying the values of
various data types.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer, while
their name must be stored as a string. Python specify the storage method for each of the standard data types
that Python provides. The following is a list of the Python-defined data types.

 Numbers
 Sequence Type
 Boolean
 Set
 Dictionary

12
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with a
Python Numbers datatype. Python offers the type() function to determine a variable's data type. The instance
() capability is utilized to check whether an item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,

1.3 Python Operators

The operator is a symbol that performs a specific operation between two operands, according to one definition.
Operators serve as the foundation upon which logic is constructed in a program in a particular programming
language. In every programming language, some operators perform several tasks. Same as other languages,
Python also has some operators, and these are given below -

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many arithmetic
operators. It includes the exponent (**) operator as well as the + (addition), - (subtraction), * (multiplication), /
(divide), % (reminder), and // (floor division) operators. Consider the following table for a detailed explanation
of arithmetic operators.
Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20

It is used to subtract the second operand from the first operand. If the first operand is
- (Subtraction) less than the second operand, the value results negative. For example, if a = 20, b = 5
=> a - b = 15

It returns the quotient after dividing the first operand by the second operand. For
/ (divide)
example, if a = 20, b = 10 => a/b = 2.0

13
It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b =
* (Multiplication)
80

It returns the reminder after dividing the first operand by the second operand. For
% (reminder)
example, if a = 20, b = 10 => a%b = 0

As it calculates the first operand's power to the second operand, it is an exponent


** (Exponent)
operator.

// (Floor division) It provides the quotient's floor value, which is obtained by dividing the two operands.

Program Code:

Now we give code examples of arithmetic operators in Python. The code is given below -

a = 32 # Initialize the value of a


b = 6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)

Addition of two numbers: 38


Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5

Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare the values of the
two operands and return a true or false Boolean value in accordance. The example of comparison operators
are ==, !=, <=, >=, >, <. In the below table, we explain the works of the operators.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= The condition is met if the first operand is smaller than or equal to the second operand.

>= The condition is met if the first operand is greater than or equal to the second operand.

14
> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.
Program Code:
Now we give code examples of Comparison operators in Python. The code is given below -
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print ('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
Program Code:

Code examples of Assignment operators in Python. The code is given below -


a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)

15
Chapter 2: Control Structures (if/else, loops, Conditional Statements)

2.1 If-else statements

Decision-making is the most important aspect of almost all the programming languages. As the name implies,
decision-making allows us to run a particular block of code for a particular decision. Here, the decisions are
made on the validity of the particular conditions. Condition checking is the backbone of decision-making.

Statement Description

The if statement is used to test a specific condition. If the condition is true, a block of code (if-
If Statement
block) will be executed.

The if-else statement is similar to if statement except the fact that, it also provides the block of
If - else
the code for the false case of the condition to be checked. If the condition provided in the if
Statement
statement is false, then the else statement will be executed.

Nested if
Nested if statements enable us to use if ? else statement inside an outer if statement.
Statement

Indentation in Python
For the ease of programming and to achieve simplicity, python does not allow the use of parentheses for the
block level code. In Python, indentation is used to declare a block. If two statements are at the same indentation
level, then they are the part of the same block. Generally, four spaces are given to indent the statements,
which are a typical amount of indentation in python.
Advertisement
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual indentation
takes place in decision-making and other stuff in python.
The if statement

The if statement is used to test a particular condition and if the condition is true, it executes a block of code
known as if-block. The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.

16
The syntax of the if-statement is given below.

if expression:
statement
Example 1
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number
Example 2 : Program to print the largest of the three numbers.
# Simple Python Program to print the largest of the three numbers.
a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
if a>b and a>c:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given a is largest");
if b>a and b>c:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given b is largest");
if c>a and c>b:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given c is largest");

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in the false case
of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

17
if condition:
#block of statements
else:
#another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote or not.
# Simple Python Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age: "))
# Here, we are taking an integer num and taking input dynamically
if age>=18:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Output:

Enter your age: 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.


# Simple Python Program to check whether a number is even or not.
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
else:
print("The Given Number is an odd number")
Output:

enter the number: 10


The Given number is even number

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

18
else:
# block of statements

Example 1
# Simple Python program to understand elif statement
number = int(input("Enter the number?"))
# Here, we are taking an integer number and taking input dynamically
if number==10:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equals to 10")
elif number==50:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 50");
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");

Example 2
# Simple Python program to understand elif statement
marks = int(input("Enter the marks? "))
# Here, we are taking an integer marks and taking input dynamically
if marks > 85 and marks <= 100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("Congrats ! you scored grade A ...")

19
elif marks > 60 and marks <= 85:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

2.2 Python Loops

The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the
loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time
required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
[Link]. Name of the loop Loop Type & Description

Repeats a statement or group of statements while a given condition is


1 While loop
TRUE. It tests the condition before executing the loop body.

This type of loop executes a code block multiple times and abbreviates the
2 For loop
code that manages the loop variable.

3 Nested loops We can iterate a loop inside another loop.

Loop Control Statements


Statements used to control loops and change the course of iteration are called control statements. All the
objects produced within the local scope of the loop are deleted when execution is completed.

Python provides the following control statements. We will discuss them later in detail.

Let us quickly go over the definitions of these loop control statements.

[Link]. Name of the control statement Description

This command terminates the loop's execution and transfers


1 Break statement
the program's control to the statement next to the loop.

This command skips the current iteration of the loop. The


statements following the continue statement are not
2 Continue statement
executed once the Python interpreter reaches the continue
statement.

20
The pass statement is used when a statement is
3 Pass statement
syntactically necessary, but no code is to be executed.

2.2.1 for Loop


Python is for loop is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary,
or other iterable objects of Python. The process of traversing a sequence is known as iteration.
Syntax of the for Loop
for value in sequence:
{ code block }
In this case, the variable value is used to hold the value of every item present in the sequence before the
iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
# Python program to show how the for loop works
# Creating a sequence which is a tuple of numbers
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
# variable to store the square of the number
square = 0
# Creating an empty list
squares = []
# Creating a for loop
for value in numbers:
square = value ** 2
squares. append(square)
print ("The list of squares is", squares)
Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Using else Statement with for Loop


As already said, a for loop executes the code block until the sequence element is reached. The statement is
written right after the for loop is executed after the execution of the for loop is complete. Only if the execution
is complete does the else statement comes into play. It will not be executed if we exit the loop or if an error is
thrown.
Code
# Python program to show how if-else statements work
string = "Python Loop"
# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)
Output:

P
y

21
t
h
If block
n

L
If block
If block
p

Now similarly, using else with for loop.

Syntax:

for value in sequence:


# executes the statements until sequences are exhausted
else:
# executes these statements when for loop is completed
Code

# Python program to show how to use else statement with for loop

# Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)

# Initiating the loop


for value in tuple_:
if value % 2 != 0:
print(value)
# giving an else statement
else:
print("These are the odd numbers present in the tuple")
Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function


With the help of the range() function, we may produce a series of numbers. range (10) will produce values
between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range (start, stop, step size). If the step
size is not specified, it defaults to 1.
Since it does not create every value it "contains" after we construct it, the range object can be characterized
as being "slow." It does provide in, len, and __getitem__ actions, but it is not an iterator.
The example that follows will make this clear.
Code

22
# Python program to show the working of range() function

print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))


Output:

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing to
iterate through the given sequence by combining it with an iterable's len() function. Here's an illustration.

Code

# Python program to iterate over a sequence with the help of indexing

tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")

# iterating over tuple_ using range() function


for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

2.2.2 While Loop


While loops are used in Python to iterate until a specified condition is met. However, the statement in the
program that follows the while loop is executed once the condition changes to false.

Syntax of the while loop is:

while <condition>:
{ code block }
All the coding statements that follow a structural command define a code block. These statements are intended
with the same number of spaces. Python groups statements together with indentation.
Code

# Python program to show how to use a while loop

23
counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")
Output:

Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops


As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the
same syntax.

Code

#Python program to show how to use else statement with the while loop
counter = 0

# Iterating through the while loop


while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed untile condition is met
# Once the condition of while loop gives False this statement will be executed
else:
print("Code block inside the else statement")
Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block


The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where we
can write the code block in a single line.

Code

# Python program to show how to write a single statement while loop


counter = 0
while (count < 3): print("Python Loops")
Loop Control Statements
Now we will discuss the loop control statements in detail. We will see an example of each control statement.

24
Continue Statement
It returns the control to the beginning of the loop.

Code

# Python program to show how the continue statement works

# Initiating the loop


for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)
Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement
It stops the execution of the loop when the break statement is reached.

Code

# Python program to show how the break statement works

# Initiating the loop


for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)
Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and
empty control statements.

Code

25
# Python program to show how the pass statement works
for a string in "Python Loops":
pass
print( 'Last Letter:', string)
Output:

Last Letter: s

Chapter 3: Functions and Modules

3.1 introduction to python functions


A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is known
as a function. An assortment of proclamations called Python Capabilities returns the specific errand.
Python functions are necessary for intermediate-level programming and are easy to define. Function
names meet the same standards as variable names do. The objective is to define a function and group-
specific frequently performed actions. Instead of repeatedly creating the same code block for various input
variables, we can call the function and reuse the code it contains with different variables. Client-
characterized and worked-in capabilities are the two primary classes of capabilities in Python. It aids in
maintaining the program's uniqueness, conciseness, and structure.
3.2 Advantages of Python Functions
Pause we can stop a program from repeatedly using the same code block by including functions.
Once defined, Python functions can be called multiple times and from any location in a program.
Our Python program can be broken up into numerous, easy-to-follow functions if it is significant.
The ability to return as many outputs as we want using a variety of arguments is one of Python's most
significant achievements.
However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.
Syntax
# An example Python Function
def function_name( parameters ):
# code block
The accompanying components make up to characterize a capability, as seen previously.

The start of a capability header is shown by a catchphrase called def.

Function_name is the function's name, which we can use to distinguish it from other functions. We will
utilize this name to call the capability later in the program. Name functions in Python must adhere to the
same guidelines as naming variables.

Using parameters, we provide the defined function with arguments. Notwithstanding, they are
discretionary.

A colon (:) marks the function header's end.

We can utilize a documentation string called docstring in the short structure to make sense of the reason
for the capability.

Several valid Python statements make up the function's body. The entire code block's indentation depth-
typically four spaces-must be the same.
A return expression can get a value from a defined function.

26
3.3 Illustration of a User-Defined Function
We will define a function that returns the argument number's square when called.
# Example Python Code for User-Defined function
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square (6)
print( "The square of the given number is: ", object_ )
Output:

The square of the given number is: 36

3.4 Calling a Function


Calling a Function To define a function, use the def keyword to give it a name, specify the arguments it
must receive, and organize the code block.

When the fundamental framework for a function is finished, we can call it from anywhere in the program.
An illustration of how to use the a_function function can be found below.

# Example Python Code for calling a function


# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)

# Calling the function we defined


print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Output:

Length of the string Functions is: 9


Length of the string Python is: 6

3.5 Pass by Reference vs. Pass by Value


In Python programming language, all parameters are passed by reference. It shows that if we modify the
worth of contention within a capability, the calling capability will similarly mirror the change. For instance,

Code

# Example Python Code for Pass by Reference vs. Value


# defining the function
def square( item_list ):
'''''''This function will find the square of items in the list'''
squares = [ ]
for l in item_list:
[Link]( l**2 )
return squares

27
# calling the defined function
my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )
Output:

Squares of the list are: [289, 2704, 64]

3.6 Function Arguments


The following are the types of arguments that we can use to call a function:

1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no worth is
provided for the contention when the capability is called. The following example demonstrates default
arguments.

Code

# Python code to demonstrate the use of default arguments


# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling the function and passing only one argument


print( "Passing only one argument" )
function(30)

# Now giving two arguments to the function


print( "Passing two arguments" )
function(50,30)
Output:

Passing only one argument


number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30

28
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a capability with
watchword contentions, the client might tell whose boundary esteem it is by looking at the boundary name.

We can eliminate or orchestrate specific contentions in an alternate request since the Python translator will
interface the furnished watchwords to connect the qualities with its boundaries. One more method for utilizing
watchwords to summon the capability() strategy is as per the following:
Code
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling function and passing arguments without using keyword


print( "Without using keyword" )
function( 50, 30)

# Calling function and passing arguments using keyword


print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:

Without using keyword


number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50

3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined positional sequence.
The number of arguments required in the method call must be the same as those provided in the function's
definition.
We should send two contentions to the capability() all put together; it will return a language structure blunder,
as seen beneath.
Code
# Python code to demonstrate the use of default arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 30
print( "Passing out of order arguments" )
function( 30, 20 )

# Calling function and passing only one argument


print( "Passing only one argument" )
try:
function( 30 )
except:

29
print( "Function needs two positional arguments" )
Output:

Passing out of order arguments


number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments

3.6 Variable-Length Arguments


We can involve unique characters in Python capabilities to pass many contentions. However, we need a
capability. This can be accomplished with one of two types of characters:
"args" and "kwargs" refer to arguments not based on keywords.
To help you understand arguments of variable length, here's an example.
Code
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
[Link]( [Link]() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )

# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
[Link]([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:

['PYTHON', 'FUNCTIONS', 'TUTORIAL']


[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]

return Statement
When a defined function is called, a return statement is written to exit the function and return the calculated
value.
Syntax:
return < expression to be returned as output >
The return statement can be an argument, a statement, or a value, and it is provided as output when a
particular job or function is finished. A declared function will return an empty string if no return statement
is written.

A return statement in Python functions is depicted in the following example.

30
Code

# Python code to demonstrate the use of return statements


# Defining a function with return statement
def square( num ):
return num**2
# Calling function and passing arguments.
print( "With return statement" )
print( square( 52 ) )
# Defining a function without return statement
def square( num ):
num**2
# Calling function and passing arguments.
print( "Without return statement" )
print( square( 52 ) )
Output:

With return statement


2704
Without return statement
None

The Anonymous Functions


Since we do not use the def keyword to declare these kinds of Python functions, they are unknown. The
lambda keyword can define anonymous, short, single-output functions.

Arguments can be accepted in any number by lambda expressions; however, the function only produces
a single value from them. They cannot contain multiple instructions or expressions. Since lambda needs
articulation, a mysterious capability can't be straightforwardly called to print.

Lambda functions can only refer to variables in their argument list and the global domain name because
they contain their distinct local domain.

In contrast to inline expressions in C and C++, which pass function stack allocations at execution for
efficiency reasons, lambda expressions appear to be one-line representations of functions.

Syntax

Lambda functions have exactly one line in their syntax:

lambda [argument1 [,argument2... .argumentn]] : expression


Below is an illustration of how to use the lambda function:
Code
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;

# Calling the function and passing values


print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:

31
Value of the function is : 50
Value of the function is : 90

Scope and Lifetime of Variables


A variable's scope refers to the program's domain wherever it is declared. A capability's contentions and
factors are not external to the characterized capability. They only have a local domain as a result.

The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same as the
lifespan of its internal variables. When we exit the function, they are taken away from us. As a result, the
value of a variable in a function does not persist from previous executions.
An easy illustration of a function's scope for a variable can be found here.
Code
# Python code to demonstrate scope and lifetime of variables
#defining a function to print a number.
def number( ):
num = 50
print( "Value of num inside the function: ", num)

num = 10
number()
print( "Value of num outside the function:", num)
Output:

Value of num inside the function: 50


Value of num outside the function: 10

Here, we can see that the initial value of num is 10. Even though the function number () changed the value
of num to 50, the value of num outside of the function remained unchanged.

This is because the capability's interior variable num is not quite the same as the outer variable (nearby to
the capability).

Despite having a similar variable name, they are separate factors with discrete extensions.
Factors past the capability are available inside the capability.

The impact of these variables is global. We can retrieve their values within the function, but we cannot
alter or change them. The value of a variable can be changed outside of the function if it is declared global
with the keyword global.

Python Capability inside Another Capability


Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same
everywhere they are used in a programming language. They can be stored in built-in data structures, used
as arguments, and in conditional expressions. If a programming language treats functions like first-class
objects, it is considered to implement first-class functions. Python lends its support to the concept of First-
Class functions.

A function defined within another is called an "inner" or "nested" function. The parameters of the outer
scope are accessible to inner functions. Internal capabilities are developed to cover them from the
progressions outside the capability. Numerous designers see this interaction as an embodiment.
Code

32
# Python code to show how to access variables of a nested functions
# defining a nested function
def word():
string = 'Python functions tutorial'
x=5
def number():
print( string )
print( x )

number()
word()

Chapter 4: Lists, Tuples, Dictionaries, and Sets

4.1 Python List


In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of values
or items. Since Python lists are mutable, we can change their elements after forming. The comma (,) and the
square brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and reliable form. A list, a
type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data formats
for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as Array List
in Java and Vector in C++. A list is a collection of items separated by commas and denoted by the symbol [].
4.2 List Declaration
Code
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]

# printing the list


print(list1)
print(list2)

# printing the type of list


print(type(list1))
print(type(list2))
Output:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >

4.3 Characteristics of Lists


The characteristics of the List are as follows:
The lists are in order.

33
The list element can be accessed via the index.
The mutable type of List is
The rundowns are changeable sorts.
The number of various elements can be stored in a list.
Ordered List Checking
Code
# example
a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
a == b
Output:

False

The indistinguishable components were remembered for the two records; however, the subsequent rundown
changed the file position of the fifth component, which is against the rundowns' planned request. False is
returned when the two lists are compared.
Code
# example
a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
a == b
Output:

True

Records forever protect the component's structure. Because of this, it is an arranged collection of things.
Let's take a closer look at the list example.
Code
# list example in detail
emp = [ "John", 102, "USA"]
Dep1 = [ "CS",10]
Dep2 = [ "IT",11]
HOD_CS = [ 10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data ...")
print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
print("printing departments ...")
print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0], Dep2[1], Dep2[0
], Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
Output:

printing employee data...


Name : John, ID: 102, Country: USA
printing departments...
Department 1:

34
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>

In the preceding illustration, we printed the employee and department-specific details from lists that we had
created. To better comprehend the List's concept, look at the code above.
4.4 List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator [] can be used to get to
the List's components. The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.

We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
The beginning indicates the beginning record position of the rundown.
The stop signifies the last record position of the rundown.
Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the value of the end parameter is the
number of elements that are "stepped" through. The default value for the step is one without a specific value.
Inside the resultant Sub List, the same with record start would be available, yet the one with the file finish will
not. The first element in a list appears to have an index of zero.
Consider the following example:
Code
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default, the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output:

35
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

In contrast to other programming languages, Python lets you use negative indexing as well. The negative
indices are counted from the right. The index -1 represents the final element on the List's right side, followed
by the index -2 for the next member on the left, and so on, until the last element on the left is reached.

Let's have a look at the following example where we will use negative indexing to access the elements of the
list.
Code
# negative indexing example
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

Negative indexing allows us to obtain an element, as previously mentioned. The first print statement in the
code above returned the rightmost item in the List. The second print statement returned the sub-list, and so
on.
4.5 Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their values, lists are Python's
most adaptable data structure. Python's append() and insert() methods can also add values to a list.
Consider the following example to update the values inside the List.
Code
# updating list values
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)

36
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also provides us the remove() method
if we do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.
Code
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

4.6 Python List Operations


The concatenation (+) and repetition (*) operators work in the same way as they were working with the strings.
The different operations of list are
Repetition
Concatenation
Length
Iteration
Membership
Let's see how the list responds to various operators.
Repetition
The redundancy administrator empowers the rundown components to be rehashed on different occasions.
Code
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:

37
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

Concatenation
It concatenates the list mentioned on either side of the operator.
Code
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

Length
It is used to get the length of the list
Code
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
Output:

Iteration
The for loop is used to iterate over the list elements.
Code
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
Output:

12
14
16
39
40

Membership
It returns true if a particular item exists in a particular list otherwise false.
Code

38
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not

print(600 in list1)
print(700 in list1)
print(1040 in list1)

print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:

False
False
False
True
True
True

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as
follows.
Code
# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each element in each iteration.
print(i)
Output:

John
David
James
Jonathan

Adding Elements to the List


The append() function in Python can add a new item to the List. In any case, the annex() capability can enhance
the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown from the client and print
the rundown on the control center.
Code
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item

39
[Link](input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Output:

Enter the number of elements in the list:10


Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18

Removing Elements from the List


The remove () function in Python can remove an element from the List. To comprehend this idea, look at the
example that follows.
Example -
Code
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
[Link](2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:

printing original list:


01234
printing the list after the removal of first element...
0134

Python List Built-in Functions


Python provides the following built-in functions, which can be used with the lists.
len()
max()
min()
len( )
It is used to calculate the length of the list.
Code
# size of the list
# declaring the list

40
list1 = [12, 16, 18, 20, 39, 40]
# finding length of the list
len(list1)
Output:

Max( )
It returns the maximum element of the list
Code
# maximum of the list
list1 = [103, 675, 321, 782, 200]
# large element in the list
print(max(list1))
Output:

782

Min( )
It returns the minimum element of the list
Code
# minimum of the list
list1 = [103, 675, 321, 782, 200]
# smallest element in the list
print(min(list1))
Output:

103

Let's have a look at the few list examples.


Example: 1- Create a program to eliminate the List's duplicate items.
Code
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
[Link](i)
print(list2)
Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Compose a program to track down the amount of the component in the rundown.
Code
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i

41
print("The sum is:",sum)
Output:

The sum is: 67


In [8]:

Example: 3- Compose the program to find the rundowns comprise of somewhere around one normal
component.
Code
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output:

The common element is: 2

4.7 Python Tuples


comma-separated group of items is called a Python triple. The ordering, settled items, and reiterations of
a tuple are to some degree like those of a rundown, but in contrast to a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the components of a tuple once they have
been assigned. On the other hand, we can edit the contents of a list.

Example

("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.


Features of Python Tuple

Tuples are an immutable data type, meaning their elements cannot be changed after they are generated.

Each element in a tuple has a specific order that will never change because tuples are ordered sequences.
Forming a Tuple:
All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis ().
Although parentheses are not required, they are recommended.

Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be
contained in a tuple.

Code

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers

42
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple


nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
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 necessary for the construction of multiples. This is known as triple pressing.

Code

# Python program to create a tuple without using parentheses


# Creating a tuple
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
# Displaying the tuple created
print(tuple_)
# Checking the data type of object tuple_
print(type(tuple_) )
# Trying to modify tuple_
try:
tuple_[1] = 4.2
except:
print(TypeError )
Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])


<class 'tuple'>
<class 'TypeError'>

The development of a tuple from a solitary part may be complex.

Essentially adding a bracket around the component is lacking. A comma must separate the element to be
recognized as a tuple.

Code

# Python program to show how to create a tuple having a single element


single_tuple = ("Tuple")
print( type(single_tuple) )

43
# Creating a tuple that has only one element
single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )
Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Accessing Tuple Elements


A tuple's objects can be accessed in a variety of ways.

Indexing

Indexing We can use the index operator [] to access an object in a tuple, where the index starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised assuming we
attempt to get to a list from the Tuple that is outside the scope of the tuple record. An index above four will
be out of range in this scenario.

Because the index in Python must be an integer, we cannot provide an index of a floating data type or any
other type. If we provide a floating index, the result will be TypeError.

The method by which elements can be accessed through nested tuples can be seen in the example below.

Code

# Python program to show how to access tuple elements


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))

# Accessing the index of a nested tuple


print(nested_tuple[0][3])
print(nested_tuple[1][1])

44
Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6

Negative Indexing
Python's sequence objects support negative indexing.
The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.
Code
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output:

Element at -1 index: Collection


Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing
Tuple slicing is a common practice in Python and the most common way for programmers to deal with
practical issues. Look at a tuple in Python. Slice a tuple to access a variety of its elements. Using the colon
as a straightforward slicing operator (:) is one strategy.
To gain access to various tuple elements, we can use the slicing operator colon (:).
Code
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
Output:

Elements between indices 1 and 3: ('Tuple', 'Ordered')


Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')

Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or remove tuple
components as a result.

45
However, the keyword del can completely delete a tuple.
Code
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as e:
print(e)
Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined

Repetition Tuples in Python


Code
# Python program to show repetition in tuples
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
Output:

Original tuple is: ('Python', 'Tuples')


New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')

Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a few ways to work with tuples
in Python. With some examples, this essay will go over these two approaches in detail.
The following are some examples of these methods.

Count () Method
The times the predetermined component happens in the Tuple is returned by the count () capability of the
Tuple.
Code
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = [Link](2)
print('Count of 2 in T1 is:', res)

46
# counting the appearance of java
res = [Link]('java')
print('Count of Java in T2 is:', res)
Output:

Count of 2 in T1 is: 5
Count of java in T2 is: 2

Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:

The thing that must be looked for.

Start: (Optional) the index that is used to begin the final (optional) search: The most recent index from
which the search is carried out

Index Method
Code
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Output:

First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6

Tuple Membership Test


Utilizing the watchword, we can decide whether a thing is available in the given Tuple.
Code
# Python program to show how to perform membership test for tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Output:

True
False
False

47
True

Iterating Through a Tuple


A for loop can be used to iterate through each tuple element.
Code
# Python program to show how to iterate over tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Iterating over tuple elements using a for loop
for item in tuple_:
print(item)

4.7 Python List Vs Tuple

This section study the major differences between lists and tuples and how to handle these two data structures.
Lists and tuples are types of data structures that hold one or more than one objects or items in a predefined
order. We can contain objects of any data type in a list or tuple, including the null data type defined by the
None Keyword.

What is a List?
In other programming languages, list objects are declared similarly to arrays. Lists do not have to be
homogeneous all the time, so they can simultaneously store items of different data types. This makes lists the
most useful tool. The list is a kind of container data Structure of Python that is used to hold numerous pieces
of data simultaneously. Lists are helpful when we need to iterate over some elements and keep hold of the
items.

What is a Tuple?

A tuple is another data structure to store the collection of items of many data types, but unlike mutable
lists, tuples are immutable. A tuple, in other words, is a collection of items separated by commas.
Because of its static structure, the tuple is more efficient than the list.

Differences between Lists and Tuples

In most cases, lists and tuples are equivalent. However, there are some important differences.

List and Tuple Syntax Differences


The syntax of a list differs from that of a tuple. Items of a tuple are enclosed by parentheses or curved
brackets (), whereas items of a list are enclosed by square brackets [].
Example Code
# Python code to show the difference between creating a list and a tuple
list_ = [4, 5, 7, 1, 7]
tuple_ = (4, 1, 8, 3, 9)
print("List is: ", list_)
print("Tuple is: ", tuple_)
Output:

List is: [4, 5, 7, 1, 7]

48
Tuple is: (4, 1, 8, 3, 9)

We declared a variable named list_, which contains a certain number of integers ranging from 1 to 10. The
list is enclosed in square brackets []. We also created a variable called tuple_, which holds a certain number
of integers. The tuple is enclosed in curly brackets (). The type() method in Python returns the data type
of the data structure or object passed to it.
Example Code
# Code to print the data type of the data structure using the type() function
print( type(list_) )
print( type(tuple_) )
Output:

<class 'list'>

<class 'tuple'>

Mutable List vs. Immutable Tuple

An important difference between a list and a tuple is that lists are mutable, whereas tuples are immutable.
What exactly does this imply? It means a list's items can be changed or modified, whereas a tuple's items
cannot be changed or modified.
We can't employ a list as a key of a dictionary because it is mutable. This is because a key of a Python
dictionary is an immutable object. As a result, tuples can be used as keys to a dictionary if required.
Let's consider the example highlighting the difference between lists and tuples in immutability and
mutability.
Example Code
# Updating the element of list and tuple at a particular index

# creating a list and a tuple


list_ = ["Python", "Lists", "Tuples", "Differences"]
tuple_ = ("Python", "Lists", "Tuples", "Differences")

# modifying the last string in both data structures


list_[3] = "Mutable"
print( list_ )
try:
tuple_[3] = "Immutable"
print( tuple_ )
except TypeError:
print( "Tuples cannot be modified because they are immutable" )
Output:

['Python', 'Lists', 'Tuples', 'Mutable']

49
Tuples cannot be modified because they are immutable

We altered the string of list_ at index 3 in the above code, which the Python interpreter updated at index 3
in the output. Also, we tried to modify the last index of the tuple in a try block, but since it raised an error,
we got output from the except block. This is because tuples are immutable, and the Python interpreter
raised TypeError on modifying the tuple.

Size Difference
Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python,
on the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than
the list. If we have a huge number of items, this makes tuples a little more memory-efficient than lists.
For example, consider creating a list and a tuple with the identical items and comparing their sizes:
Example Code
# Code to show the difference in the size of a list and a tuple
#creating a list and a tuple
list_ = ["Python", "Lists", "Tuples", "Differences"]
tuple_ = ("Python", "Lists", "Tuples", "Differences")
# printing sizes
print("Size of tuple: ", tuple_.__sizeof__())
print("Size of list: ", list_.__sizeof__())
Output:

Size of tuple: 28
Size of list: 52

Available Functions
Tuples have fewer built-in functions than lists. We may leverage the in-built function dir([object] to access
all the corresponding methods for the list and tuple.
Example Code
# printing directory of list
dir(list_)
Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__',


'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Example Code
# Printing directory of a tuple
print( dir(tuple_), end = ", " )
Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',


'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',

50
'__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'count', 'index']

As we can observe, a list has many more methods than a tuple. With intrinsic functions, we can perform
insert and pop operations and remove and sort items from the list not provided in the tuple.

Tuples and Lists: Key Similarities

They both hold collections of items and are heterogeneous data types, meaning they can contain multiple
data types simultaneously. They are both ordered, which implies the items or objects are maintained in
the same order as they were placed until changed manually. Because they're both sequential data
structures, we can iterate through the objects they hold; hence, they are iterables. An integer index,
enclosed in square brackets [index], can be used to access objects of both data types.

4.8 Python Set


A Python set is the collection of the unordered items. Each element in the set must be unique, immutable,
and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its
creation.

Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index. However, we can print them all together, or we can get
the list of elements by looping through the set.

Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python
also provides the set() method, which can be used to create the set by the passed sequence.

Example 1: Using curly braces


Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Example 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:

51
print(i)
Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}


<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary, set)
can't be a member of set. Consider the following example.

# Creating a set which have immutable elements


set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
Output:

<class 'set'>

Traceback (most recent call last)


<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))

TypeError: unhashable type: 'list'


In the above code, we have created two sets, the set set1 have immutable elements and set2 have one
mutable element as a list. While checking the type of set2, it raised an error, which means set can contain
only immutable elements.

Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary as
well. So Python provides the set() method used without an argument to create an empty set.

# Empty curly braces will create dictionary


set3 = {}
print(type(set3))

# Empty set using set() function


set4 = set()
print(type(set4))
Output:
Advertisement

<class 'dict'>

52
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.

set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)
Output:

Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}


In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it remove
the duplicity from the set.

Adding items to the set


Python provides the add() method and update() method which can be used to add some particular item to
the set. The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set. Consider the following example.

Example: 1 - Using add() method

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
[Link]("July");
[Link] ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January
To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.

Python Set Operations


Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference. Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.
Union of two Sets

53
To combine two or more sets into one set in Python, use the union() function. All of the distinctive
characteristics from each combined set are present in the final set. As parameters, one or more sets may
be passed to the union() function. The function returns a copy of the set supplied as the lone parameter if
there is just one set. The method returns a new set containing all the different items from all the
arguments if more than one set is supplied as an argument.

Consider the following example to calculate the union of two sets.


Example 1: using union | operator
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Output:
{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}
Python also provides the union() method which can also be used to calculate the union of two sets.
Consider the following example.
Advertisement
Example 2: using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print([Link](Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}
Now, we can also make the union of more than two sets using the union() function, for example:
Program:
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}

# Find the common elements between the three sets


common_elements = [Link](set2, set3)

# Print the common elements


print(common_elements)
Output:
{1, 2, 3, 4, 5}
The intersection of two sets
To discover what is common between two or more sets in Python, apply the intersection() function. Only
the items in all sets being compared are included in the final set. One or more sets can also be used as
the intersection() function parameters. The function returns a copy of the set supplied as the lone
parameter if there is just one set. The method returns a new set that only contains the elements in all the
compared sets if multiple sets are supplied as arguments.
The intersection of two sets can be performed by the and & operator or the intersection() function. The
intersection of the two sets is given as the set of the elements that common in both sets.

54
Consider the following example.
Example 1: Using & operator
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Output:
{'Monday', 'Tuesday'}
Example 2: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print([Link](set2)) #prints the intersection of the two sets
Output:
{'Martin', 'David'}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = [Link](set2)
print(set3)
Output:
{1,2,5}
Similarly, as the same as union function, we can perform the intersection of more than two sets at a time,
For Example:
Program
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}

# Find the common elements between the three sets


common_elements = [Link](set2, set3)

# Print the common elements


print(common_elements)
Output:
{3}
The intersection_update() method
The intersection_update() method removes the items from the original set that are not present in both
the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, the intersection() method returns a new
set.
Consider the following example.
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}

55
a.intersection_update(b, c)

print(a)
Output:
{'castle'}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator
or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes
the resulting set will be obtained that element of A, which is not present in the set B.

Consider the following example.


Example 1 : Using subtraction ( - ) operator
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:
{'Thursday', 'Wednesday'}
Example 2 : Using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print([Link](Days2)) # prints the difference of the two sets Days1 and Days2
Output:
{'Thursday', 'Wednesday'}
Symmetric Difference of two sets
In Python, the symmetric Difference between set1 and set2 is the set of elements present in one set or
the other but not in both sets. In other words, the set of elements is in set1 or set2 but not in their
intersection.
The Symmetric Difference of two sets can be computed using Python's symmetric_difference() method.
This method returns a new set containing all the elements in either but not in both. Consider the following
example:

Example - 1: Using ^ operator


a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}

56
Example - 2: Using symmetric_difference() method
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
In Python, you can compare sets to check if they are equal, if one set is a subset or superset of another,
or if two sets have elements in common.
Here are the set comparison operators available in Python:
==: checks if two sets have the same elements, regardless of their order.
!=: checks if two sets are not equal.
<: checks if the left set is a proper subset of the right set (i.e., all elements in the left set are also in the
right set, but the right set has additional elements).
<=: checks if the left set is a subset of the right set (i.e., all elements in the left set are also in the right
set).
>: checks if the left set is a proper superset of the right set (i.e., all elements in the right set are also in
the left set, but the left set has additional elements).
>=: checks if the left set is a superset of the right set (i.e., all elements in the right set are also in the left).
Consider the following example.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}

#Days1 is the superset of Days2 hence it will print true.


print (Days1>Days2)

#prints false since Days1 is not the subset of Days2


print (Days1<Days2)

#prints false since Days2 and Days3 are not equivalent


print (Days2 == Days3)
Output:
True
False
False
FrozenSets
In Python, a frozen set is an immutable version of the built-in set data type. It is similar to a set, but its
contents cannot be changed once a frozen set is created.
Frozen set objects are unordered collections of unique elements, just like sets. They can be used the
same way as sets, except they cannot be modified. Because they are immutable, frozen set objects can
be used as elements of other sets or dictionary keys, while standard sets cannot.
One of the main advantages of using frozen set objects is that they are hashable, meaning they can be
used as keys in dictionaries or as elements of other sets. Their contents cannot change, so their hash
values remain constant. Standard sets are not hashable because they can be modified, so their hash
values can change. Frozen set objects support many of the assets of the same operation, such as union,
intersection, Difference, and symmetric Difference. They also support operations that do not modify the
frozen set, such as len(), min(), max(), and in.
Consider the following example to create the frozen set.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")

57
for i in Frozenset:
print(i);
[Link](6) #gives an error since we cannot change the content of Frozenset after creation
Output:
<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "[Link]", line 6, in <module>
[Link](6) #gives an error since we can change the content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'
Frozenset for the dictionary
If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from
the dictionary and returns a frozenset that contains the key of the dictionary as its elements.
Consider the following example.
Dictionary = {"Name":"John", "Country":"USA", "ID":101}
print(type(Dictionary))
Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary
print(type(Frozenset))
for i in Frozenset:
print(i)
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
Set Programming Example
Example - 1: Write a program to remove the given number from the set.
my_set = {1,2,3,4,5,6,12,24}
n = int(input("Enter the number you want to remove"))
my_set.discard(n)
print("After Removing:",my_set)
Output:
Enter the number you want to remove:12
After Removing: {1, 2, 3, 4, 5, 6, 24}
Example - 2: Write a program to add multiple elements to the set.
set1 = set([1,2,4,"John","CS"])
[Link](["Apple","Mango","Grapes"])
print(set1)
Output:
{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}
Example - 3: Write a program to find the union between two set.
set1 = set(["Peter","Joseph", 65,59,96])
set2 = set(["Peter",1,2,"Joseph"])
set3 = [Link](set2)
print(set3)
Output:

58
{96, 65, 2, 'Joseph', 1, 'Peter', 59}
Example- 4: Write a program to find the intersection between two sets.
set1 = {23,44,56,67,90,45,"Javatpoint"}
set2 = {13,23,56,76,"Sachin"}
set3 = [Link](set2)
print(set3)
Output:
{56, 23}
Example - 5: Write the program to add element to the frozenset.
set1 = {23,44,56,67,90,45,"Javatpoint"}
set2 = {13,23,56,76,"Sachin"}
set3 = [Link](set2)
print(set3)
Output:
TypeError: 'frozenset' object does not support item assignment
Above code raised an error because frozensets are immutable and can't be changed after creation.
Example - 6: Write the program to find the issuperset, issubset and superset.
set1 = set(["Peter","James","Camroon","Ricky","Donald"])
set2 = set(["Camroon","Washington","Peter"])
set3 = set(["Peter"])

issubset = set1 >= set2


print(issubset)
issuperset = set1 <= set2
print(issuperset)
issubset = set3 <= set2
print(issubset)
issuperset = set2 >= set3
print(issuperset)
Output:
False
False
True
True

Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating
real-world data arrangements where a certain value exists for a given key.
 The data is stored as key-value pairs using a Python dictionary.
 This data structure is mutable
 The components of dictionary were made using keys and values.
 Keys must only have one component.
 Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The
keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are
ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
Creating the Dictionary

59
Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches
as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its
value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of
an immutable object.
Let's see an example to create a dictionary and print its content.
Code
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output

<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}

Python provides the built-in function dict() method which is also used to create the dictionary.
The empty curly braces {} is used to create empty dictionary.
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output

Empty Dictionary:
Create Dictionary by using dict():
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

Dictionary with each item as a pair:

60
{4: 'Rinku', 2: 'Singh'}

Accessing the dictionary values


To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be
used to obtain the values because they are unique from one another. The following method can be used
to access dictionary values.
Code
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output

ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO

Python provides us with an alternative to use the get() method to access the dictionary values. It would
give the same result as given by the indexing.
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key]
= value and the value can both be modified. An existing value can also be updated using the update()
method.
Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the
dictionary's newly added keys.
Let's see an example to update the dictionary values.
Example - 1:
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# with a single Key

61
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Output

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:
Code
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");

62
print("printing the new data");
print(Employee)
Output

<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the details of the new
employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}

Deleting Elements using del Keyword


The items of the dictionary can be deleted by using the del keyword as given below.
Code
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output

<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.

The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.
Deleting Elements using pop() Method
A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items using this
unordered, mutable data type by using their keys. The pop() method is one of the ways to get rid of
elements from a dictionary. In this post, we'll talk about how to remove items from a Python dictionary
using the pop() method.

63
The value connected to a specific key in a dictionary is removed using the pop() method, which then returns
the value. The key of the element to be removed is the only argument needed. The pop() method can be
used in the following ways:
Code
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = [Link](2)
print(Dict1)
Output

{1: 'JavaTpoint', 3: 'Website'}

Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items. In contrast
to the clear() method, which removes all of the elements from the entire dictionary, popitem() removes any
element from a dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
Code
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)
Output

Name
Age
salary
Company

Example 2
Code
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"} for x in Employee:
print(Employee[x])
Output

John
29
25000
WIPRO

Example - 3
Code
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in [Link]():
print(x)

64
Output

John
29
25000
WIPRO

Example 4
Code
#for loop to print the items of the dictionary by using items() method
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in [Link]():
print(x)
Output

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')

Properties of Dictionary Keys


In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a
single key, then the value which is last assigned is considered as the value of the key.
Consider the following example.
Code
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
"John"}
for x,y in [Link]():
print(x,y)
Output

Name John
Age 29
Salary 25000
Company WIPRO

The key cannot belong to any mutable object in Python. Numbers, strings, or tuples can be used as the
key, however mutable objects like lists cannot be used as the key in a dictionary.
Consider the following example.
Code
Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department
ID"}
for x,y in [Link]():
print(x,y)
Output

Traceback (most recent call last):


File "[Link]", line 1, in
Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department
ID"}

65
TypeError: unhashable type: 'list'

Built-in Dictionary Functions


A function is a method that can be used on a construct to yield a value. Additionally, the construct is
unaltered. A few of the Python methods can be combined with a Python dictionary.
The built-in Python dictionary methods are listed below, along with a brief description.
len()
The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each
key-value pair.
Code
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
len(dict)
Output

any()
Like how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have
a Boolean expression that evaluates to True.
Code
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
any({'':'','':'','3':''})
Output

True

all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value.
Code
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
all({1:'',2:'','':''})
Output

False

sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series of the dictionary's keys.
The ascending sorting has no effect on the original Python dictionary.
Code
dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
sorted(dict)
Output

[ 1, 5, 7, 8]

Built-in Dictionary methods

66
The built-in python dictionary methods along with the description and Code are given below.
clear()
It is mainly used to delete all the items of the dictionary.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
[Link]()
print(dict)
Output

{}

copy()
It returns a shallow copy of the dictionary which is created.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = [Link]()
print(dict_demo)
Output

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

pop()
It mainly eliminates the element using the defined key.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# pop() method
dict_demo = [Link]()
x = dict_demo.pop(1)
print(x)
Output

{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

popitem()
removes the most recent key-value pair entered
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# popitem() method
dict_demo.popitem()
print(dict_demo)
Output

67
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

keys()
It returns all the keys of the dictionary.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# keys() method
print(dict_demo.keys())
Output

dict_keys([1, 2, 3, 4, 5])

items()
It returns all the key-value pairs as a tuple.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
print(dict_demo.items())
Output

dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])

get()
It is used to get the value specified for the passed key.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict_demo.get(3))
Output

Facebook

update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({3: "TCS"})
print(dict_demo)
Output

68
{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}

values()
It returns all the values of the dictionary with respect to given input.
Code
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict_demo.values())
Output

dict_values(['Hcl', 'WIPRO', 'TCS'])

Chapter 5: Object-Oriented Programming (Classes, Objects, Inheritance)

69
5.1 Python OOPs Concepts

Like other general-purpose programming languages, Python is also an object-oriented language since its
beginning. It allows us to develop applications using an Object-Oriented approach.
An object-oriented paradigm is to design the program using classes and objects. The object is related to real-
word entities such as book, house, pencil, etc. The oops concept focuses on writing the reusable code. It is a
widespread technique to solve the problem by creating objects.
Major principles of object-oriented programming system are given below.
 Class
 Object
 Method
 Inheritance
 Polymorphism
 Data Abstraction
 Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and
methods. For example: if you have an employee class, then it should contain an attribute and method, i.e. an
email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard,
chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-
in attribute __doc__, which returns the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the following example.
Example:
class car:
def __init__(self,modelname, year):
[Link] = modelname
[Link] = year
def display(self):
print([Link],[Link])

c1 = car("Toyota", 2016)
[Link]()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes modelname and year.
We have created a c1 object to access the class attribute. The c1 object will allocate memory for these values.
We will learn more about class and object in the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is not unique to class instances.
Any object type can have methods.

Inheritance

70
Inheritance is the most important aspect of object-oriented programming, which simulates the real-world
concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent
object.
By using inheritance, we can create a class which uses all the properties and behavior of another class. The
new class is known as a derived class or child class, and the one whose properties are acquired is known as
a base class or parent class.
It provides the re-usability of the code.

Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means shape. By
polymorphism, we understand that one task can be performed in different ways. For example - you have a
class animal, and all animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in a
sense and depends on the animal. So, the abstract "animal" concept does not actually "speak", but specific
animals (like dogs and cats) have a concrete implementation of the action "speak".

Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to
methods and variables. In encapsulation, code and data are wrapped together within a single unit from being
modified by accident.

Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because
data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give
names to things so that the name captures the core of what a function or a whole program does.
Object-oriented vs. Procedure-oriented Programming languages
The difference between object-oriented and procedure-oriented programming is given below:
Advertisement
Index Object-oriented Programming Procedural Programming

Object-oriented programming is the problem-


Procedural programming uses a list of instructions to do
1. solving approach and used where computation
computation step by step.
is done by using objects.

It makes the development and maintenance In procedural programming, It is not easy to maintain the
2.
easier. codes when the project becomes lengthy.

It doesn't simulate the real world. It works on step by


It simulates the real world entity. So real-world
3. step instructions divided into small parts called
problems can be easily solved through oops.
functions.

It provides data hiding. So it is more secure


Procedural language doesn't provide any proper way for
4. than procedural languages. You cannot access
data binding, so it is less secure.
private data from anywhere.

Example of object-oriented programming Example of procedural languages are: C, Fortran,


5.
languages is C++, Java, .Net, Python, C#, etc. Pascal, VB etc.

5.2 Classes and Objects in Python

71
Python is an object-oriented programming language that offers classes, which are a potent tool for writing
reusable code. To describe objects with shared characteristics and behaviours, classes are utilised. We
shall examine Python's ideas of classes and objects in this article.
Classes in Python:
In Python, a class is a user-defined data type that contains both the data itself and the methods that may
be used to manipulate it. In a sense, classes serve as a template to create objects. They provide the
characteristics and operations that the objects will employ.
Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms,
doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the
building can be seen as a class, and we can create as many objects of this class.
Creating Classes in Python
In Python, a class can be created by using the keyword class, followed by the class name. The syntax to
create a class is given below.
Syntax
class ClassName:
#statement_suite
In Python, we must notice that each class is associated with a documentation string which can be accessed
by using <class-name>.__doc__. A class contains a statement suite including fields, constructor,
function, etc. definition.
Example:
Code:
class Person:
def __init__(self, name, age):
# This is the constructor method that is called when creating a new Person object
# It takes two parameters, name and age, and initializes them as attributes of the object
[Link] = name
[Link] = age
def greet(self):
# This is a method of the Person class that prints a greeting message
print("Hello, my name is " + [Link])
Name and age are the two properties of the Person class. Additionally, it has a function called greet that
prints a greeting.

Objects in Python:
An object is a particular instance of a class with unique characteristics and functions. After a class has
been established, you may make objects based on it. By using the class constructor, you may create an
object of a class in Python. The object's attributes are initialised in the constructor, which is a special
procedure with the name __init__.

Syntax:
# Declare an object of a class
object_name = Class_Name(arguments)
Example:
Code:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
print("Hello, my name is " + [Link])

# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)

72
[Link]()
Output:

"Hello, my name is Ayan"

T
he self-parameter

The self-parameter refers to the current instance of the class and accesses the class variables. We can
use anything instead of self, but it must be the first parameter of any function which belongs to the class.
_ _init_ _ method

In order to make an instance of a class in Python, a specific function called __init__ is called. Although it
is used to set the object's attributes, it is often referred to as a constructor.
The self-argument is the only one required by the __init__ method. This argument refers to the newly
generated instance of the class. To initialise the values of each attribute associated with the objects, you
can declare extra arguments in the __init__ method.
Class and Instance Variables
All instances of a class exchange class variables. They function independently of any class methods and
may be accessed through the use of the class name. Here's an illustration:
Code:
class Person:
count = 0 # This is a class variable

def __init__(self, name, age):


[Link] = name # This is an instance variable
[Link] = age
[Link] += 1 # Accessing the class variable using the name of the class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
Output:

Whereas, instance variables are specific to each instance of a class. They are specified using the self-
argument in the __init__ method. Here's an illustration:
Code:
class Person:
def __init__(self, name, age):
[Link] = name # This is an instance variable
[Link] = age
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
print([Link])
Output:

Ayan

73
30

Class variables are created separately from any class methods and are shared by all class copies. Every
instance of a class has its own instance variables, which are specified in the __init__ method utilising the
self-argument.
Conclusion:
In conclusion, Python's classes and objects notions are strong ideas that let you write reusable
programmes. You may combine information and capabilities into a single entity that is able to be used to
build many objects by establishing a class. Using the dot notation, you may access an object's methods
and properties after it has been created. You can develop more logical, effective, and manageable code
by comprehending Python's classes and objects.

5.3 Python Constructor


A constructor is a special type of method (function) which is used to initialize the instance members of the
class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in
Python. It is used to create an object.
Constructors can be of two types.
 Parameterized Constructor
 Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also verify that
there are enough resources for the object to perform any start-up task.
Creating the constructor in python
The method the __init__() simulates the constructor of the class. This method is called when the class is
instantiated. It accepts the self-keyword as a first argument, which allows accessing the attributes or
method of the class. We can pass any number of arguments at the time of creating the class object,
depending upon the __init__() definition. It is mostly used to initialize the class attributes. Every class must
have a constructor, even if it simply relies on the default constructor.
Consider the following example to initialize the Employee class attributes.
Example
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)

# accessing display() method to print employee 1 information

[Link]()

# accessing display() method to print employee 2 information


[Link]()
Output:

ID: 101
Name: John

74
ID: 102
Name: David

5.4 Counting the number of objects of a class


The constructor is called automatically when we create the object of the class. Consider the following
example.
Example
class Student:
count = 0
def __init__(self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])
Output:

The number of students: 3

Python Non-Parameterized Constructor


The non-parameterized constructor uses when we do not want to manipulate the value or the constructor
that has only self as an argument. Consider the following example.
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the following
example.
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()
Output:

This is parametrized constructor

75
Hello John

5.5 Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that becomes the default
constructor. It does not perform any task but initializes the objects. Consider the following example.
Example
class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,[Link])

st = Student()
[Link]()
Output:

101 Joseph

More than One Constructor in Single class


Let's have a look at another scenario, what happen if we declare the two same constructors in the class.
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")

st = Student()
Output:

The Second Constructor

In the above code, the object st called the second constructor whereas both have the same configuration.
The first method is not accessible by the st object. Internally, the object of the class will always call the
last constructor if the class has multiple constructors.
Note: The constructor overloading is not allowed in Python.

Python built-in class functions


The built-in functions defined in the class are described in the following table.
SN Function Description

1 getattr(obj,name,default) It is used to access the attribute of the object.

It is used to set a particular value to the specific attribute of


2 setattr(obj, name,value)
an object.

76
3 delattr(obj, name) It is used to delete a specific attribute.

4 hasattr(obj, name) It returns true if the object contains some specific attribute.
Example
class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age

# creates the object of the class Student


s = Student("John", 101, 22)

# prints the attribute name of the object s


print(getattr(s, 'name'))

# reset the value of attribute age to 23


setattr(s, "age", 23)

# prints the modified value of age


print(getattr(s, 'age'))

# prints true if the student contains the attribute with name id

print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')

# this will give an error since the attribute age has been deleted
print([Link])
Output:

John
23
True
AttributeError: 'Student' object has no attribute 'age'

Built-in class attributes


Along with the other attributes, a Python class also contains some built-in class attributes which provide
information about the class.
The built-in class attributes are given in the below table.
SN Attribute Description

It provides the dictionary containing the information about the class


1 __dict__
namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.

77
4 __module__ It is used to access the module in which, this class is defined.

5 __bases__ It contains a tuple including all base classes.


Example
class Student:
def __init__(self,name,id,age):
[Link] = name;
[Link] = id;
[Link] = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%([Link],[Link]))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:

None
{'name': 'John', 'id': 101, 'age': 22}
__main__

5.6 Python Inheritance


Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability
to the program because we can use an existing class to create a new class instead of creating it from
scratch.
In inheritance, the child class acquires the properties and can access all the data members and functions
defined in the parent class. A child class can also provide its specific implementation to the functions of
the parent class. In this section of the tutorial, we will discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived
class name. Consider the following syntax to inherit a base class into the derived class.

Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following
syntax.

Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>

78
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
Output:

dog barking
Animal Speaking

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is
archived when a derived class inherits another derived class. There is no limit on the number of levels up
to which, the multi-level inheritance is archived in python.

The syntax of multi-level inheritance is given below.

Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>

Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()

79
[Link]()
[Link]()
Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
Output:

30
200

80
0.5

The issubclass(sub,sup) method


The issubclass(sub, sup) method is used to check the relationships between the specified classes. It
returns true if the first class is the subclass of the second class, and false otherwise.
Consider the following example.

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:

True
False

The isinstance (obj, class) method


The isinstance() method is used to check the relationship between the objects and classes. It returns true
if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.
Consider the following example.

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Output:

True

81
Method Overriding
We can provide some specific implementation of the parent class method in our child class. When the
parent class method is defined in the child class with some specific implementation, then the concept is
called method overriding. We may need to perform method overriding in the scenario where the different
definition of a parent class method is needed in the child class.
Consider the following example to perform method overriding in python.

Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
[Link]()
Output:

Barking

Real Life Example of method overriding


class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;

class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",[Link]());
print("SBI Rate of interest:",[Link]());
print("ICICI Rate of interest:",[Link]());
Output:

Bank Rate of interest: 10


SBI Rate of interest: 7
ICICI Rate of interest: 8

Data abstraction in python


Abstraction is an important aspect of object-oriented programming. In python, we can also perform data
hiding by adding the double underscore (___) as a prefix to the attribute which is to be hidden. After this,
the attribute will not be visible outside of the class through the object.
Consider the following example.

82
Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
[Link]()
Output:

The number of employees 2


AttributeError: 'Employee' object has no attribute '__count'

5.7 abstraction in python

Abstraction is used to hide the internal functionality of the function from the users. The users only interact with
the basic implementation of the function, but inner working is hidden. User is familiar with that "what function
does" but they don't know "how it does."
In simple words, we all use the smartphone and very much familiar with its functions such as camera, voice-
recorder, call dialing, etc., but we do not know how these operations are happening in the background. Let's
take another example - When we use the TV remote to increase the volume. We don't know how pressing a
key increases the volume of the TV. We only know to press the "+" button to increase the volume.
That is exactly the abstraction that works in the object-oriented concept.
Why Abstraction is Important?
In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity. It also
enhances the application efficiency. Next, we will learn how we can achieve abstraction using the Python
program.

Abstraction classes in Python


In Python, abstraction can be achieved by using abstract classes and interfaces.
A class that consists of one or more abstract method is called the abstract class. Abstract methods do not
contain their implementation. Abstract class can be inherited by the subclass and abstract method gets its
definition in the subclass. Abstraction classes are meant to be the blueprint of the other class. An abstract
class can be useful when we are designing large functions. An abstract class is also helpful to provide the
standard interface for different implementations of components. Python provides the abc module to use the
abstraction in the Python program. Let's see the following syntax.
Syntax
1. from abc import ABC
2. class ClassName(ABC):
We import the ABC class from the abc module.

Abstract Base Classes

83
An abstract base class is the common application program of the interface for a set of subclasses. It can be
used by the third-party, which will provide the implementations such as with plugins.
Working of the Abstract Classes
Unlike the other high-level language, Python doesn't provide the abstract class itself. We need to import the
abc module, which provides the base for defining Abstract Base classes (ABC). The ABC works by decorating
methods of the base class as abstract.
Example -
# Python program demonstrate
# abstract base class work
from abc import ABC, abstractmethod
class Car(ABC):
def mileage(self):
pass

class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")

class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")

# Driver code
t= Tesla ()
[Link]()

r = Renault()
[Link]()

s = Suzuki()
[Link]()
d = Duster()
[Link]()
Output:

The mileage is 30kmph


The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph

Explanation -
In the above code, we have imported the abc module to create the abstract base class. We created the Car
class that inherited the ABC class and defined an abstract method named mileage(). We have then inherited
the base class from the three different subclasses and implemented the abstract method differently. We
created the objects to call the abstract method.
Let's understand another example.

84
Let's understand another example.
Example -
# Python program to define
# abstract class

from abc import ABC

class Polygon(ABC):

# abstract method
def sides(self):
pass
class Triangle(Polygon):

def sides(self):
print("Triangle has 3 sides")

class Pentagon(Polygon):

def sides(self):
print("Pentagon has 5 sides")

class Hexagon(Polygon):
def sides(self):
print("Hexagon has 6 sides")
class square(Polygon):
def sides(self):
print("I have 4 sides")
# Driver code
t = Triangle()
[Link]()

s = square()
[Link]()

p = Pentagon()
[Link]()

k = Hexagon()
[Link]()
Output:

Triangle has 3 sides


Square has 4 sides
Pentagon has 5 sides
Hexagon has 6 sides

Explanation -
In the above code, we have defined the abstract base class named Polygon and we also defined the abstract
method. This base class inherited by the various subclasses. We implemented the abstract method in each
subclass. We created the object of the subclasses and invoke the sides() method. The hidden

85
implementations for the sides() method inside the each subclass comes into play. The abstract
method sides() method, defined in the abstract class, is never invoked.
Points to Remember
Below are the points which we should remember about the abstract base class in Python.
o An Abstract class can contain the both method normal and abstract method.
o An Abstract cannot be instantiated; we cannot create objects for the abstract class.
Abstraction is essential to hide the core functionality from the users. We have covered the all the basic concepts
of

Chapter 6: Case Study of Object Oriented Programming

- Inheritance
- Types of inheritance
- Functional requirement
- Non-functional requirements

86
Chapter 7: Array and lists

 Introduction to arrays and links lists


An array is a data structure that stores a collection of elements of the same data type in contiguous memory
locations

87
Characterisics of arrys
 Homogeneeous : All elements are of the same data type
 Contiguous : Elements are stored in adjecent memory locations
 Fixed size : array size is determined at compile time
 Indexed : elements are accessed using an index or subscript
 Types of arrays
 One dimentional array (1D) : single row or column of elements
 Muti dimentional array (2D, 3D), etc.) : matrix or cube of lements
 Dynamic array : resizable arrays, often implemented using pointers
 Array operations
 Indexing : accessing elements using their index
 Assignment : assigning values to elements
 Interations : looping through elements
 Search : finding specifics elements
 Sort : arranging elements in order
 Array methods
Array methods are functions that operate on arrays, allowing you to manipulate, transform, and interact with
array data.
Common array methods
- Push : adds elements to the end of an array
- Pop : removes the last element from an array
- Shift : removes the first element from an array
- Unshift : adds elements to the beginning of an array
- Sort : sorts array elements in ascending or desceding order
- Reverse : reverse the order of array elements
- Splice : removes or replaces elements within an array
- Slice : creates a new array from a subset of elements
- Indexof : Finds the index of a specific elements
- Includes : checks if an element exists within an array
- Mapt : applies a function to each element returning a new array
- Reduce : Reduces an array to a single value
- Every : checks if all elements meet a condition
- Some : checks if any elements meet a conditions
 Linked list
In python, a list is a data structure that stores an ordered collection of values, which can be of any data type,
including strings, integers, float, and other lists.

Types of link lists


 Ordered : lists maintain the order of elements
 Indexed : elements are accessed using their index (0-based)
 Mutable : lists can be modified after creation
 Dynamic : lists can grow or shrink dynamically
 Heterogeneous : List scan store elements of different data types
Creating a lists
1. Square brackets [] : my_list =[1,2,3,4,5]
2. list() function : my_list =list((1, 2, 3, 4, 5))
3. list comprehension : my_list = [x**2 for x in range(5)]
Link lists operations

88
 Indexing : my_list[0] access the first elements.
 Slicing :my_list[1 :3] accesses elements at indices 1 and 2
 Append :my_list. append(6) adds an element to the end
 Insert : my_list. insert(2, 7) insert an element at index 2.
 Remove :my_list. remove (4) removes the first occurrence of 4.
 Sort : my_list. sort() sorts the list in ascending order
 Reverse : my_list.reverse() reverse the list
Link list methods
 Append()
 Extend()
 Insert()
 Remove()
 Pop()
 Index()
 Count()
 Sort()
 Reverse()

Chapter 8: Django Framework for Web Development

 Introducton to django framework


 Django architecture
 Django components
 Django features
 Django tools
 Django deployment

89
Chapter 9: Numpy framework

 Introduction to numpy and pandas


 Key features
 Nympy data structure
 Nympy operations
 Numpy functions

90
Chapter 10: Pandas Framework for Data analysis

 Introduction to pandas
 Pandas features
 Pandas data structure
 Pandas operations
 Pandas functions

91

You might also like