Python Programming
Python Programming
1
PLANNING DU DEROULEMENT DES ENSEIGNEMENTS
IDENTIFICATION DE L’ENSEIGNANT
Email :ernestmbmb@[Link]
COURSE OBJECTIVES
8) Apply python to various domains (examples data science, AI, Machine learning)
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
STUDENT ’ASSIGNMENTS
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 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
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
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
5
10
15
11
The values will be assigned in the order in which variables appear.
<type 'int'>
<type 'str'>
<type 'float'>
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,
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
// (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 -
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:
15
Chapter 2: Control Structures (if/else, loops, Conditional 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");
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
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:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
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 ?")
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
This type of loop executes a code block multiple times and abbreviates the
2 For loop
code that manages the loop variable.
Python provides the following control statements. We will discuss them later in detail.
20
The pass statement is used when a statement is
3 Pass statement
syntactically necessary, but no code is to be executed.
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
P
y
21
t
h
If block
n
L
If block
If block
p
Syntax:
# 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)
3
9
3
9
7
These are the odd numbers present in the tuple
22
# Python program to show the working of range() function
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
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
LOOPS
SEQUENCE
CONDITION
RANGE
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
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
Code
#Python program to show how to use else statement with the while loop
counter = 0
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
Code
24
Continue Statement
It returns the control to the beginning of the loop.
Code
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
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
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.
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:
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.
Code
27
# calling the defined function
my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )
Output:
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
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)
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 )
29
print( "Function needs two positional arguments" )
Output:
# 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:
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.
30
Code
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
31
Value of the function is : 50
Value of the function is : 90
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:
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.
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()
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:
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]
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:
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
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:
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
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:
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 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
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
42
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
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
Essentially adding a bracket around the component is lacking. A comma must separate the element to be
recognized as a tuple.
Code
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'>
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
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:
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:
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 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:
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
True
False
False
47
True
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.
In most cases, lists and tuples are equivalent. However, there are some important differences.
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'>
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
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:
Example Code
# Printing directory of a tuple
print( dir(tuple_), end = ", " )
Output:
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.
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.
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.
51
print(i)
Output:
<class 'set'>
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.
<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:
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.
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}
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.
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"}
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'>
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"])
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'}
60
{4: 'Rinku', 2: 'Singh'}
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)
61
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
Empty Dictionary:
{}
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'}
<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
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')
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
65
TypeError: unhashable type: 'list'
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]
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
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
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
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
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
It makes the development and maintenance In procedural programming, It is not easy to maintain the
2.
easier. codes when the project becomes lengthy.
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:
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
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.
[Link]()
ID: 101
Name: John
74
ID: 102
Name: David
75
Hello John
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
Output:
101 Joseph
st = Student()
Output:
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.
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
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'
77
4 __module__ It is used to access the module in which, this class is defined.
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
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
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...
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
class 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
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
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
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:
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:
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.
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:
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
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:
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
- Inheritance
- Types of inheritance
- Functional requirement
- Non-functional requirements
86
Chapter 7: Array and lists
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.
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()
89
Chapter 9: Numpy framework
90
Chapter 10: Pandas Framework for Data analysis
Introduction to pandas
Pandas features
Pandas data structure
Pandas operations
Pandas functions
91