0% found this document useful (0 votes)
16 views238 pages

Py-23 02 22

The document provides an introduction to Python, a high-level, interpreted programming language known for its ease of learning and versatility across various applications such as web development, data analysis, and GUI programming. It outlines key features of Python, including its interpreted nature, cross-platform compatibility, and support for object-oriented programming. Additionally, the document covers Python basics such as variables, input/output operations, data types, and operators.

Uploaded by

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

Py-23 02 22

The document provides an introduction to Python, a high-level, interpreted programming language known for its ease of learning and versatility across various applications such as web development, data analysis, and GUI programming. It outlines key features of Python, including its interpreted nature, cross-platform compatibility, and support for object-oriented programming. Additionally, the document covers Python basics such as variables, input/output operations, data types, and operators.

Uploaded by

mamidigunna765
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 238

Python

By
N.RAJENDER

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 1


Python Introduction

• Python is a general purpose, high-level, interpreted programming language developed


by Guido van Rossum in the late 1980s at the National Research Institute for
Mathematics and Computer Science in the Netherlands.

• Python is one of the most popular and widely used programming language used for set
of tasks including console based, GUI based, web programming and data analysis.

• Python is a easy to learn and simple programming language so even if you are new to
programming, you can learn python without facing any problems.

• Fact: Python is named after the comedy television show Monty Python's Flying Circus.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 2


Features of Python
Python provides lots of features that are listed below.
1.Easy to Learn and Use
Python is easy to learn and use compared with other programming languages.
It is developer-friendly and high-level programming language.
2.Interpreted Language
Python is an interpreted language because no need of compilation. This makes
debugging easy and thus suitable for beginners.
3.Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix
and Macintosh etc. So, we can say that Python is a portable language.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 3


4.Free and Open Source
The Python interpreter is developed under an open-source license, making it
free to install, use, and distribute.
5.Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects
come into existence.
6.GUI Programming Support
Graphical user interfaces can be developed using Python.
7.Integrated
It can be easily integrated with languages like C, C++, and JAVA etc.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 4


Why Python?

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.
• Python syntax can be executed by writing directly in the Command Line:
• print("Hello, World!")
• Or by creating a python file on the server, using the .py file extension, and
running
16/04/2025 it in the Command Line
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 5
Python Applications

• Python is a general-purpose programming language that makes it applicable in almost all domains
of software development. Python as a whole can be used to develop any type of applications.
• Here, we are providing some specific application areas where python can be applied.
• Web Applications
• Desktop GUI Applications
• Software Development
• Scientific and Numeric
• Business Applications
• Console Based Application
• Audio or Video based Applications
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 6
Basics of Python

• Comments in python:
• Comments are non-executable statements in Python. It means neither the python
compiler nor the PVM will execute them. Comments are intended for human
understanding, not for the compiler or PVM. Therefore, they are called non-executable
statements.
• There are two types of commenting features available in Python: These are single-line
comments and multi-line comments.
1.Single Line Comments.
• A single-line comment begins with a hash (#) symbol and is useful in mentioning that
the whole line should be considered as a comment until the end of the line.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 7
• Example:
# This is single line comment.
print("Hello Python").
2. Multi Line Comment
Multi lined comment can be given inside triple quotes. The must start at beginning of the
line.
Example:
'''This
is
Multi line comment'''
print("Hello Python")
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 8
Python Indentation

• Indentation refers to the spaces at the beginning of a code line.


• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
• Example
if 5 > 2:
• print ("Five is greater than two!")
• Python will give you an error if you skip the indentation:
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 9
• Example
• Syntax Error:
• Example
• Syntax Error:
• if 5 > 2:
• print ("Five is greater than two!")
• The number of spaces is up to you as a programmer, but it has to be at
least one.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 10


Python Variables

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example

x=5

y = "python"

Variables do not need to be declared with any particular type, and can even change type after they have been
set.

Example

x=4 # x is of type int

x = "Salary"
16/04/2025# x is now of type str Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 11
• Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
type(x)
type(y)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 12


Many Values to Multiple Variables
• Python allows you to assign values to multiple variables in one line:
• Example
• x, y, z = "Orange", "Banana", "Cherry"
• Note: Make sure the number of variables matches the number of values, or
else you will get an error.
One Value to Multiple Variables
• And you can assign the same value to multiple variables in one line:
• Example
• x = y = z = "Orange"

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 13


Input-Output Operations in Python
• Input and Output operations are performed using two built-in functions
• print( ) - Used for output operation.
• input( ) - Used for input operations.
1. print()
• The print() function prints the specified message to the screen, or other standard output
device.
• The message can be a string, or any other object, the object will be converted into a string
before written to the screen.
• Syntax:
print(object(s), separator=separator, end=end, file=file, flush=flush)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 14
• When we use the print( ) function to display a message, the string can be
enclosed either in the single quotation or double quotation.
• print('how are you?')
• print("have fun with python")
• The following example shows that how to display the combination of
message and variable value
• x = 10
• print('The value of variable num1 is ' + x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 15


2. input()
• The Python provides a built-in function input( ) to perform input operations.
Syntax:
input(prompt)
• Use the prompt parameter to write a message before the input.
• x = input('Enter your name:')
• print('Hello, ' + x).

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 16


Numbers
• Number stores numeric values. Python creates Number type variable
when a number is assigned to a variable.
• There are three numeric types in Python:
int
float
Complex.
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
a = 10
b = -12
c = 16/04/2025
123456789 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 17
float
• Float or "floating point number" is a number, positive or negative, containing
one or more decimals.
X = 1.0
Y = 12.3
Z = -13.4
complex
• Complex numbers are written with a "j" as the imaginary part.
A = 2+5j
B = -3+4j
C = -6j

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 18


Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
‘KITSW' is the same as “kitsw".
Eg: a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 19
String Length
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
txt = “python"
print(“p" in txt)
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use
the keyword not in.
txt = “python"
print(“p"
16/04/2025 not in txt)Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 20
• Python slicing is about obtaining a sub-string from the
given string by slicing it respectively from start to end.
Python slicing can be done in two ways.
slice() Constructor
Extending Indexing.
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the
increment between each index for slicing.
Return
16/04/2025
Type: Returns a Mr.N.Rajender,Asst.Prof,Dept
sliced object of IT,KITSW
containing elements
21
in the given range only.
String = “Information Technology”
String ='ASTRING'

# Using slice constructor


s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 22
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string both syntax wise and execution wise.
Syntax
string[start : end : step]
start, end and step have the same mechanism as slice() constructor.

String =“Information Technology”

# Using indexing sequence


print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])

# Prints string in reverse


print("\n Reverse String")
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 23
print(String[::-1])
• Remove Whitespace
The strip() method removes any whitespace from the beginning
or the end:
Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.

a = “ Information Technology "


print(a.strip()) # returns “Information Technology"

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 24


• Python Booleans.
Booleans represent one of two values: True or False.
You can evaluate any expression in Python, and get one of
two answers, True or False.
print(10 > 9)
print(10 == 9)
print(10 < 9)
Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give
you True or False in return.
print(bool("Hello"))
print(bool(15))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 25


Operators in Python

• Operators are used to perform operations on variables and values.


Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 26


..

Arithmetic operators

Arithmetic operators are used to perform arithmetic operations between two operands

Operator Description
+ (addition) Add two operands

- (subtraction) Subtract right operand from the left

*(multiplication) Multiply two operands

/ (divide) Divide left operand by the right one (always


results into float)

%( reminder) Modulus - remainder of the division of left


operand by the right

// (floor division) Floor division - division that results into whole


number adjusted to the left in the number line

** (exponent) Exponent - left operand raised to the power of


16/04/2025
right
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 27
x = 55
y=9
print(x // y)floor división.
print(x /y)divide operation.
x=2
y=5
print(x ** y) #same as 2*2*2*2*2

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 28


2. Assignment Operators
• The assignment operators are used to assign the value of the right expression
to the left operand.
Operator Description
= (Assigns to) Assigns values from right side operands to left side operand.

+= (Assignment after Addition) It adds right operand to the left operand and assign the result to left operand.

-= (Assignment after Subtraction) It subtracts right operand from the left operand and assign the result to left
operand.

*= (Assignment after Multiplication) It multiplies right operand with the left operand and assign the result to left
operand.

/= (Assignment after Division) It divides left operand with the right operand and assign the result to left
operand.

%= (Assignment after Modulus) It takes modulus using two operands and assign the result to left operand.

**= (Assignment after Exponent) Performs exponential (power) calculation on operators and assign value to
the left operand.

//= (Assignment after floor division) It performs floor division on operators and assign value to the left operand.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 29
Identity Operators
• Identity operators are used to compare the objects, not if they are equal,
but if they are actually the same object, with the same memory location.

Operator Description
is Returns true if both variables are the same object ( if id(x) equals id(y) )

is not Returns true if both variables are not the same object

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 30


Membership Operators

• Membership operators are used to test if a sequence is presented in an


object:
Operator
Description
In it Returns True if a sequence with the specified value is present in the object (list, tuple, or dictionary)
not in it Returns True if a sequence with the specified value is not present in the object (list, tuple, or dictionary)

x = 'Hello world'
print('H' in x)
print('hello' not in x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 31


Taking input in Python

• provides us with two inbuilt functions to read the input from the keyboard.

input ( prompt )
raw_input ( prompt )

input ( ) : This function first takes the input from the user and then evaluates the
expression, which means Python automatically identifies whether user entered a
string or a number or list. If the input provided is not correct then either syntax error
or exception is raised by python.

val = input("Enter your value: ")


print(val)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 32
• Jupyter Notebook is an open-source, web-based interactive environment,
which allows us to create and share documents that contain code,
mathematical equations, graphics, maps, plots, visualizations, and
narrative text. It integrates with many programming languages like
Python, PHP, R, C#, etc.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 33


List Sequence in Python

• In python, a list can be defined as a collection of values or items of different


types. The items in the list are separated with the comma (,) and enclosed
with the square brackets [].
List = [value1, value2, value3,….]
L0 = [] #creates empty list
L1 = [123,"python", 3.7]
L2 = [1, 2, 3, 4, 5, 6]
L3 = ["C Programing","Java","Python"]
print(L0)
print(L1)
print(L2)
print(L3)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 34
• List indexing
• The indexing are processed in the same way as it happens with the strings.
The elements of the list can be accessed by using the slice operator [].
• The index starts from 0, the first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 35


List Operators

Operator
Description
+ It is known as concatenation operator used to concatenate two lists
* It is known as repetition operator. It concatenates the multiple copies of the same list.
[] It is known as slice operator. It is used to access the list item from list.
[:] It is known as range slice operator. It is used to access the range of list items from list.
in It is known as membership operator. It returns if a particular item is present in the
specified list.
not in It is also a membership operator and It returns true if a particular list item is not present in
the list.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 36


num=[1,2,3,4,5]
lang=['python','c','java','php']
print(num+lang)
print(num*2)
print(lang[2])
print(lang[1:4])
print('cpp' in lang)
print(6 not in num)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 37


How to add or change elements to a list?
We can use assignment operator (=) to change an item or a range of items.
num=[1,2,3,4,5]
print(num)
num[2]=30
print(num)
num[1:3]=[25,36]
print(num)
num[4]="Python"
print(num)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 38


How to delete or remove elements from a list?
Python allows us to delete one or more items in a list by using the del keyword.
num=[1,2,3,4,5]
print(num)
del num[1]
print(num)
del num[1:3]
print(num)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 39


List Functions
Python provides the following built-in functions which can be used with the lists.
len()
max()
min()
list()
sum()
sorted()
append()
remove()
sort()
reverse()
count()
index()
insert()
pop()
clear()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 40
len()
In Python len() is used to find the length of list,i.e it returns the number of
items in the list.
Syntax:len(list)
Eg:-num=[1,2,3,4,5,6]
print(“length of list :”,len(num))o/p?
max()
In Python max() is used to find maximum value in the list
Syntax: max(list)
Eg:-num=[1,2,3,4,5,6]
lang=['java','c','python','cpp']
print("Max of list :",max(num))
print("Max
16/04/2025 of list :",max(lang)) Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 41
min()
In Python min() is used to find minimum value in the list
Syntax:min(list)
Eg:- num=[1,2,3,4,5,6]
lang=['java','c','python','cpp’]
print("Min of list :",min(num))
print("Min of list :",min(lang))
sum()
In python, sum(list) function returns sum of all values in the list. List values
must in number type.
num=[1,2,3,4,5,6]
print(“sum of list items :”,sum(num))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 42
sorted()
In python, sorted(list) function is used to sort all items of list in an ascending order.
Syntax: sorted(list).
eg:-num=[1,3,2,4,6,5]
lang=['java','c','python','cpp’]
print(sorted(num))
print(sorted(lang)
list ()
The list() method takes sequence types and converts them to lists. This is used to
convert a given string or tuple into list.
Syntax:list(sequence)
Eg:- str="python"
list1=list(str)
16/04/2025 print(list1) Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 43
append ()
In python append() method adds an item to the end of the list.
Syntax:list.append(item)
eg:-num=[1,2,3,4,5]
lang=['python','c','java','php’]
num.append(6)
print(num)
lang.append("cpp")
print(lang)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 44


remove()
In python remove() method removes the first item from the list which is equal
to the passed value. It throws an error if the item is not present in the list.
Syntax:list.remove(item)
Eg:- num=[1,2,3,4,5]
lang=['python','c','java','php','c’]
num.remove(2)
print(num)
lang.remove("c") # first occurence will remove
print(lang)
lang.remove("cpp")
print(lang)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 45
sort()
In python sort() method sorts the list elements. It also sorts the items into descending and
ascending order. It takes an optional parameter 'reverse' which sorts the list into descending order.
By default, list sorts the elements into ascending order.
Syntax: list.sort ([reverse=true]) -reverse, which displays items in descending
Eg:- lang = ['p', 'y', 't', 'h', 'o','n'] # Char list
even = [6,8,2,4,10] # int list
print(lang)
print(even)
lang.sort()
even.sort()
print("\nAfter Sorting:\n")
print(lang)
print(even)
print("In Descending Order :\n")
even.sort(reverse=True)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 46
print(even)
reverse()
In python reverse() method reverses elements of the list. If the list is empty, it
simply returns an empty list. After reversing the last index value of the list will
be present at 0 index.
Syntax:list. Reverse ()
Eg:- lang = ['p', 'y', 't', 'h', 'o','n’]
lang = ['p', 'y', 't', 'h', 'o','n’]
print("After reverse")
lang.reverse()
print(lang)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 47


count()
In python count() method returns the number of times element appears in the
list. If the element is not present in the list, it returns 0.
Syntax:list.count(item)
num=[1,2,3,4,3,2,2,1,3,4,5,7,8]
cnt=num.count(2)
print("Count of 2 is:",cnt)
cnt=num.count(10)
print("Count of 10 is:",cnt)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 48


insert()
In python insert() method inserts the element at the specified index in the list.
The first argument is the index of the element before which to insert the
element.
Syntax:list.insert(i,x)
i : index at which element would be inserted.
x : element to be inserted.
Eg:- num=[10,20,30,40,50]
num.insert(4,60)
print("updated list is :",num)
num.insert(7,70)
print("updated list is :",num)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 49
pop()
In python pop() element removes an element present at specified index from
the list. It returns the popped element.
Syntax:list.pop([i])
Eg:- num=[10,20,30,40,50]
num.pop()
print("updated list is :",num)
num.pop(2)
print("updated list is :",num)
num.pop(7)
print("updated list is :",num)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 50


clear()
In python clear() method removes all the elements from the list. It clears the list
completely and returns nothing.
Syntax:list.clear()
Eg:- num=[10,20,30,40,50]
num.clear()
print("After clearing ",num)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 51


Tuple Sequence in Python

In Python, Tuple is used to store the sequence of immutable python objects.


Tuple is similar to lists since the value of the items stored in the list can be
changed ,where as the tuple is immutable and the value of the items stored in
the tuple cannot be changed.
A tuple can be written as the collection of comma-separated values enclosed
with the small brackets.
Syntax: Tuple= (value1, value2…)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 52


T1 = ()
T2 = (10, 30, 20, 40, 60)
T3 = ("C", "Java", "Python")
T4 = (501,"abc", 19.5)
T5 = (90,)
print(T1)
print(T2)
print(T3)
print(T4)
print(T5)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 53


• Tuple indexing:
The indexing and slicing in tuple are similar to lists. The indexing in the tuple
starts from 0 and goes to length (tuple) - 1.
The items in the tuple can be accessed by using the slice operator. Python also
allows us to use the colon operator to access multiple items in the tuple.

Unlike other languages, python provides us the flexibility to use the negative
indexing also. The negative indices are counted from the right. The last
element (right most) of the tuple has the index -1, its adjacent left element is
present at the index -2 and so on until the left most elements is encountered.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 54
Tuple Operators
Operator Description
+ It is known as concatenation operator used to concatenate two tuples

* It is known as repetition operator. It concatenates the multiple copies of the same tuple.

[] It is known as slice operator. It is used to access the item from tuple.

[:] It is known as range slice operator. It is used to access the range of items from tuple.

in It is known as membership operator. It returns if a particular item is present in the specified


tuple.

not in It is also a membership operator and It returns true if a particular item is not present in the
tuple.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 55


num=(1,2,3,4,5)
lang=('python','c','java','php')
print(num+lang)
print(num*2)
print(lang[2])
print(lang[1:4])
print('cpp' in lang)
print(6 not in num)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 56


• How to add or remove elements to a list?
Unlike lists, the tuple items cannot be updated or deleted as tuples are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
mytuple=('python','c','java','php')
mytuple[3]="html"
#'tuple' object does not support item assignment
print(mytuple)
del mytuple[3]
# 'tuple' object doesn't support item deletion
print(mytuple)
del mytuple
#deletes entire tuple
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 57
Tuple Functions

Python provides the following built-in functions which can be used with
the tuples.
len()
max()
min()
tuple()
sum()
sorted()
index()
count()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 58
len()
In Python len() is used to find the length of tuple,i.e it returns the number of
items in the tuple.
Syntax:len(tuple)
num=(1,2,3,4,5,6)
print(“length of tuple :”,len(num))
max()
In Python max() is used to find maximum value in the tuple.
Syntax:max(tuple)
num=(1,2,3,4,5,6)
lang=('java','c','python','cpp')
print("Max of tuple :",max(num))
print("Max
16/04/2025 of tuple :",max(lang))
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 59
min()
In Python min() is used to find minimum value in the tuple.
Syntax:min(tuple)
num=(1,2,3,4,5,6)
lang=('java','c','python','cpp')
print("Min of tuple :",min(num))
print("Min of tuple :",min(lang))
sum()
In python, sum(tuple) function returns sum of all values in the tuple. Tuple
values must in number type.
Syntax:sum(tuple)
num=(1,2,3,4,5,6)
print(“sum
16/04/2025 of tuple items :”,sum(num))
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 60
sorted()
In python, sorted (tuple) function is used to sort all items of tuple in an
ascending order. It also sorts the items into descending and ascending order. It
takes an optional parameter 'reverse' which sorts the tuple into descending
order.
Syntax: sorted (tuple[,reverse=True])
num=(1,3,2,4,6,5)
lang=('java','c','python','cpp')
print(sorted(num))
print(sorted(lang))
print(sorted(num,reverse=True))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 61


tuple (sequence)
The tuple() method takes sequence types and converts them to tuples. This is
used to convert a given string or list into tuple.
Syntax:tuple(sequence)
str="python"
tuple1=tuple(str)
print(tuple1)
num=[1,2,3,4,5,6]
tuple2=tuple(num)
print(tuple2)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 62


count()
In python count() method returns the number of times element appears in the
tuple. If the element is not present in the tuple, it returns 0.
Syntax:tuple.count (item).
num=(1,2,3,4,3,2,2,1,3,4,5,7,8)
cnt=num.count(2)
print("Count of 2 is:",cnt)
cnt=num.count(10)
print("Count of 10 is:",cnt)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 63


index()
In python index () method returns index of the passed element. This method
takes an argument and returns index of it. If the element is not present, it raises
a ValueError.
If tuple contains duplicate elements, it returns index of first occurred element.
This method takes two more optional parameters start and end which are used
to search index within a limit.
lang = ('p', 'y', 't', 'h', 'o','n','p','r','o','g','r','a','m')
print("index of t is:",lang.index('t'))
print("index of p is:",lang.index('p'))
print("index of p is:",lang.index('p',3,10))
print("index of p is:",lang.index('z'))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 64
Conditional Statements in Python
Conditional Statements in Python performs different computations or actions depending on
conditions.

In python, the following are conditional statements


if
if – else
if – elif –else
Indentation:
For the ease of programming and to achieve simplicity, python doesn't 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.
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
16/04/2025
at the same level indentation.
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 65
If statement
The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.
Syntax: if expression:
statement
Eg:- a = 33
b = 200
if b > a:
print ("b is greater than a")

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 66


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.

Syntax: if expression:
#block of statements
else:
#another block of statements

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 67


age = int (input("Enter your age : "))
if age >= 18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 68


If – elif - else 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.

if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 69
marks = int(input("Enter the marks :"))
if marks > 85 and marks <= 100:
print("Congrats! you scored grade A..")
elif marks > 60 and marks <= 85:
print("You scored grade B + ..")
elif marks > 40 and marks <= 60:
print("You scored grade B ..")
elif (marks > 30 and marks <= 40):
print("You scored grade C ..")
else:
print("Sorry you are fail ?")
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 70
Loop Statements in Python
Sometimes we may need to alter the flow of the program. If the execution of
a specific code may need to be repeated several numbers of times then we
can go for loop statements.
For this purpose, the python provide various types of loops which are capable
of repeating some specific code several numbers of times. Those are,
while loop
for loop
while loop
With the while loop we can execute a set of statements as long as a condition
is true. The while loop is mostly used in the case where the number of
iterations is not known in advance.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 71


Syntax: while expression:
Statement(s)
i=1;
while i<=3:
print(i);
i=i+1;

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 72


Using else with while loop
Python enables us to use the while loop with the else block also. The else
block is executed when the condition given in the while statement becomes
false.
Syntax:
while expression:
Statements
else:
Statements

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 73


i=1;
while i<=3:
print (i)
i=i+1;
else: print("The while loop terminated");

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 74


for loop

The for loop in Python is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures like
list, tuple, or dictionary.
Syntax: for iterating_var in sequence:
statement(s)
Eg:- i=1
n=int(input("Enter n value : "))
for i in range(i,n):
print(i)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 75


Using else with for loop
Python allows us to use the else statement with the for loop which can be
executed only when all the iterations are exhausted. Here, we must notice
that if the loop contains any of the break statement then the else statement
will not be executed.
Syntax: for iterating_var in sequence:
statements
else:
statements
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted");
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 76
• The range() function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified
number.
Example: range(6) means the values from 0 to 5.
range(2,6) means the values from 2 to 5.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 77


Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner
loop is executed n number of times for every iteration of the outer loop.

Syntax:
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 78


n = int(input("Enter the no.of rows you want to print : "))
for i in range(0,n):
for j in range(0,i+1):
print("*",end="")
print()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 79


break statement :
The break is a keyword in python which is used to bring the program
control out of the loop. The break statement breaks the loops one by
one, i.e., in the case of nested loops, it breaks the inner loop first and
then proceeds to outer loops.

In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the
loop.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 80


i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 81


continue statement :
• The continue statement skips the remaining lines of code inside the
loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a
particular condition.In other words, The continue statement in python
is used to bring the program control to the beginning of the loop.
• Syntax:
continue

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 82


Example:
str1 = input("Enter any String : ")
for i in str1:
if i == 'h':
continue;
print(i,end=" ");

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 83


Example Program:
Aim: Program to print odd numbers using continue statement.

Example:
num = 0
print("Odd numbers in between 1 to 10")
while(num < 10):
num = num + 1
if (num % 2) == 0:
continue
print(num)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 84
Set Sequence in Python

In python, the set can be defined as the unordered collection of various items enclosed
within the curly braces. The elements of the set cannot be duplicate. The elements of
the python set must be immutable.

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 items with the curly braces.

Syntax:
Set={value1, value2….}
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 85
Example:
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)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 86


Set Operators

• In Python, we can perform various mathematical operations on


python sets like union, intersection, difference, etc

Operator Description
| Union Operator
& Intersection Operator
- Difference Operator:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 87


Union (|) Operator

• The union of two sets are calculated by using the or (|) operator. The
union of the two sets contains the all the items that are present in
both the sets.

Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1 | Days2)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 88


Intersection (&) Operator

• The & (intersection) operator is used to calculate the intersection of


the two sets in python. The intersection of the two sets are given as
the set of the elements that common in both sets.

Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1 & Days2)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 89


Difference (-) Operator

The difference of two sets can be calculated by using the subtraction (-)
operator. The resulting set will be obtained by removing all the
elements from set 1 that are present in set 2.

Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1 - Days2)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 90


Set Functions
• Python contains the following methods to be used with the sets. Those are

• len(set)
• max(set)
• min(set)
• sum(set)
• sorted(set)
• set()
• add()
• update()
• discard()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 91
• remove()
• pop()
• clear()
• union()
• intersection()
• difference()
• issubset()
• issuperset()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 92


len()
In Python len() is used to find the length of set,i.e it returns the number
of items in the set.
Syntax:len(set)
Example:
num={1,2,3,4,5,6}
print(“length of set :”,len(num))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 93


max()
In Python max() is used to find maximum value in the set.

Syntax: max(set)

Example:
num={1,2,3,4,5,6}
lang={'java','c','python','cpp'}
print("Max of set :",max(num))
print("Max of set :",max(lang))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 94


min()
In Python min() is used to find minimum value in the set.
Syntax:min(set)
Example:
num={1,2,3,4,5,6}
lang={'java','c','python','cpp'}
print("Min of set :",min(num))
print("Min of set :",min(lang))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 95


sum()
In python, sum(set) function returns sum of all values in the set. Set
values must in number type.

Syntax:sum(set)

Example:
num={1,2,3,4,5,6}
print(“sum of set items :”,sum(num))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 96


sorted()
In python, sorted (set) function is used to sort all items of set in an ascending order. It
also sorts the items into descending and ascending order. It takes an optional
parameter 'reverse' which sorts the set into descending order.

Syntax:
sorted (set[,reverse=True])

Example:
num={1,3,2,4,6,5}
lang={'java','c','python','cpp'}
print(sorted(num))
print(sorted(lang))
print(sorted(num,reverse=True))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 97
set()
The set() method takes sequence types and converts them to sets. This is used to convert a given string
or list or tuple into set.

Syntax:
set(sequence)

Example:
set1=set("PYTHON")
print(set1)
days=["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"]
set2 = set(days)
print(set2)
days=("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun")
set3 = set(days)
print(set3)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 98
add()
In python, the add() method used to add some particular item to the set.

Syntax:set.add (item)

Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("\n printing the original set ... ")
print(Days)
Days.add("Saturday");
Days.add("Sunday");
print("\n Printing the modified set...");
print(Days)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 99
update()
Python provides the update () method to add more than one item in
the set.
Syntax:set.update ([item1, item2…])
Example:
Months={"Jan","Feb","Mar","Apr"}
print("\n Printing the original set ... ")
print(Months)
Months.update (["May","Jun","Jul"])
print("\n Printing the modified set...");
print(Months)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 100
discard()
Python provides discard () method which can be used to remove the items from the set. If item
doesn't exist in the set, the python will not give the error. The program maintains its control flow.

Syntax:set.discard (item)

Example:
Months={"Jan","Feb","Mar","Apr"}
print("\n printing the original set ... ")
print(Months)
Months.discard("Apr")
print("\n Printing the modified set...");
print(Months)
Months.discard("May") #doesn’t give error
print("\n Printing the modified set...");
print(Months)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 101
remove()
Python provides remove () method which can be used to remove the items from the set. If item
doesn't exist in the set, the python will give the error.

Syntax:set.remove (item)

Example:
Months={"Jan","Feb","Mar","Apr"}
print("\n printing the original set ... ")
print(Months)
Months.remove("Apr")
print("\n Printing the modified set...");
print(Months)
Months.remove("May") #it give error
print("\n Printing the modified set...");
print(Months)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 102
pop()
In Python, pop () method is used to remove the item. However, this method will
always remove the last item.

Syntax:set.pop ()

Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("\n printing the original set ... ")
print(Days)
Days.pop()
print("\n Printing the modified set...");
print(Days)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 103
clear()
In Python, clear () method is used to remove the all items in set.

Syntax:set.clear ()

Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("\n printing the original set ... ")
print(Days)
Days.clear()
print("\n Printing the modified set...");
print(Days)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 104
union ()
In Python, the union () method is used to perform union of two sets.
The union of the two sets contains the all the items that are present in
both the sets.
Syntax:set1.union (set2)
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1.union(Days2))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 105


intersection ()
In Python, the intersection () is used to calculate the intersection of the
two sets in python. The intersection of the two sets is given as the set
of the elements that common in both sets.

Syntax:set1.intersection (set2)

Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1.intersection(Days2))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 106


difference ()
The difference of two sets can be calculated by using the difference ()
method. The resulting set will be obtained by removing all the
elements from set 1 that are present in set 2.

Syntax:set1.difference (set2)

Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1.difference(Days2))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 107


issubset()
The issubset() method returns True if all elements of a set are present
in another set (passed as an argument). If not, it returns False.

Syntax:set1.issubset (set2)

Example:
set1={1,2,3,4}
set2={1,2,3,4,5,6,7,8,9}
print(set1.issubset(set2))
print(set2.issubset(set1))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 108
issuperset()
The issuperset () method returns True if a set has every elements of
another set (passed as an argument). If not, it returns False.

Syntax:set1.issuperset (set2)

Example:
set1={1,2,3,4}
set2={1,2,3,4,5,6,7,8,9}
print(set1.issuperset(set2))
print(set2.issuperset(set1))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 109


Dictionary Sequence in Python
• In python a dictionary is the collection of key-value pairs where the value can be any
python object whereas the keys are the immutable python object, i.e., Numbers,
string or tuple.

• The dictionary can be created by using multiple key-value pairs which are separated by
comma(,) and enclosed within the curly braces {}.

• Syntax:Dict={key1:value1, key2:value2, …….}

• Example:
• student = {"Name": "abc", "Age": 21, "Rollno":56,"Branch":“IT"}
• print(student)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 110
Accessing the dictionary values
The data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys
as keys are unique in the dictionary.

Example:
student = {"Name": “abc", "Age": 21, "Rollno":56,"Branch":“IT"}
print("Name : ",student["Name"])
print("Age : ",student["Age"])
print("RollNo : ",student["Regno"])
print("Branch : ",student["Branch"])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 111


Updating dictionary values
The dictionary is a mutable data type, and its values can be updated by
using the specific keys.

Example:
student = {"Name": “abc", "Age": 22, "Rollno":56,"Branch":“IT"}
print("printing student data .... ")
print(student)
student["Name"]=“xyz"
print("printing updated data .... ")
print(student)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 112


Deleting dictionary values
The items of the dictionary can be deleted by using the del keyword.

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("printing student data .... ")
print(student)
del student["Branch"]
print("printing the modified information ")
print(student)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 113


Accessing the dictionary values using loops
A dictionary can be iterated using the for loop.We can able to access
only keys, only values and both keys&values.

print all the keys of a dictionary

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("Keys are :")
for x in student:
print(x)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 114
print all the values of a dictionary
Example:
print("values are :")
for x in student:
print(student[x])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 115


print all the Keys & values of a dictionary

Example:
print("Key and values are :")
for x,y in student.items():
print(x,y)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 116


Dictionary Functions
Python supports following in-bulit functions, Those are

len()
copy()
get()
keys()
items()
values()
update()
pop()
clear()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 117
len()
In python, len() function is used to find length of given dictionary.

Syntax:len(dictionary)

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("Length of Dictionary is:",len(student))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 118


copy()
It returns another copy of given dictionary.

Syntax:dictionary.copy()

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
student2=student.copy()
print(student2)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 119


get()
In python, get() is used to get the value of specified key form dictionary.

Syntax:dictionary.get()

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("Name is :",student.get("Name"))
print("RegNo is :",student.get("Regno"))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 120


keys()
In python keys() method is used to fetch all the keys from the dictionary

Syntax:dictionary.keys()

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
for x in student.keys():
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 121


items()
In python items() method returns a new view of the dictionary. This
view is collection of key value tuples.

Syntax:dictionary.items()

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
for x in student.items():
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 122


values()
In python values() method is used to collect all the values from a
dictionary.

Syntax:Dictionary.values()

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
for x in student.values():
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 123


update()
In python update() method updates the dictionary with the key and value
pairs. It inserts key/value if it is not present. It updates key/value if it is
already present in the dictionary.

Syntax:Dictionary.update({key:value,….})

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
student.update({"Regno":590})
student.update({"phno":56895})
print(student)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 124
• pop()
• In python pop() method removes an element from the dictionary. It removes the
element which is associated to the specified key.
• If specified key is present in the dictionary, it remove and return its value.
• If the specified key is not present, it throws an error KeyError.

• Syntax: Dictionary.pop(key)

• Example:
• student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
• student.pop('Age')
• print(student)
• student.pop('hallno')
• print(student)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 125
clear()
In python, clear() is used to delete all the items of the dictionary.

Syntax:Dictionary.clear()

Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print(student)
student.clear()
print(student)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 126


Functions in Python
A function can be defined as the organized block of reusable code which can be
called whenever required. In other words, Python allows us to divide a large
program into the basic building blocks known as function.

Python provide us various inbuilt functions like range() or print(). Although, the
user can able to create functions which can be called user-defined functions.

Creating Function
In python, a function can be created by using def keyword.

Syntax: def my_function():


Statements
return statement
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 127
The function block is started with the colon (:) and all the same level
block statements remain at the same indentation.

Example:
def sample(): #function definition
print ("Hello world")

sample() #function calling

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 128


The information into the functions can be passed as the parameters.
The parameters are specified in the parentheses. We can give any
number of parameters, but we have to separate them with a comma.

Example:
def welcome(name):
print("function with one parameter")
print("welcome : ",name)
welcome("Guest")

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 129


Example:
def sum (a,b):
return a+b;

#taking values from the user


a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 130


Built-in Functions in Python
The Python supports several built-in functions, those are
bin()
hex()
oct()
ord()
eval()
chr()
abs()
int()
float()
str()
list()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 131
tuple()
set()
len()
max()
min()
sum()
sorted()
input()
range()
type()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 132


NumPy
• NumPy is a Python library.
• NumPy is used for working with arrays.
• NumPy is short for "Numerical Python".
• library consisting of multidimensional array objects and a collection of
routines for processing those arrays.
• Using NumPy, mathematical and logical operations on arrays can be
performed.
• NumPy is a Python package.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 133


• NumPy has in-built functions for linear algebra, fourier transform and random
number generation.
• NumPy was created in 2005 by Travis Oliphant. It is an open source project and you
can use it freely.

Why Use NumPy?

• In Python we have lists that serve the purpose of arrays, but they are slow to process.
• NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
• The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.
• Arrays are very frequently used in data science, where speed and resources are very
important.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 134
Why is NumPy Faster Than Lists?
• NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
• This behavior is called locality of reference in computer science.
• This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.
Import NumPy
• Once NumPy is installed, import it in your applications by adding the import
keyword:
• import numpy
• Now NumPy is imported and ready to use.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 135


Example

import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 136


NumPy as np
• NumPy is usually imported under the np alias.
• alias: In Python alias are an alternate name for referring to the same thing.
• Create an alias with the as keyword while importing:
• import numpy as np
• Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) #print(np.__version__)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 137
0-D Arrays
• 0-D arrays, or Scalars, are the elements in an array. Each value in an array is
a 0-D array.

• Example
#Create a 0-D array with value 1220
import numpy as np
arr = np.array(1220)
print(arr)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 138


1-D Arrays
• An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
array.
• These are the most common and basic arrays.
• Example
#Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 139


2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
Example
#Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 140


3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.

Example
#Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:

import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 141
Access Array Elements

Array indexing is the same as accessing an array element.


You can access an array element by referring to its index number.
The indexes in NumPy arrays start with 0, meaning that the first element has
index 0, and the second has index 1 etc.
Example
Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 142


Access 2-D Arrays

To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the row
represents the dimension and the index represents the column.
Example
Access the element on the first row, second column
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 143


NumPy Array Slicing
• Slicing in python means taking elements from one given index to another given index.
• We pass slice instead of index like this: [start:end].
• We can also define the step, like this: [start:end:step].
• If we don't pass start its considered 0.
• If we don't pass end its considered length of array in that dimension
• If we don't pass step its considered 1.

Example
• Slice elements from index 1 to index 5 from the following array:
• import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5]
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 144
Example
#Slice elements from index 4 to the end of the array:
• import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])

Example
#Slice elements from the beginning to index 4 (not included):
• import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[:4]
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 145
Negative Slicing
Use the minus operator to refer to an index from the end:
Example
#Slice from the index 3 from the end to index 1 from the end:
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[-3:-1])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 146


STEP
Use the step value to determine the step of the slicing:
Example
Return every other element from index 1 to index 5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
print(arr[::2])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 147


Slicing 2-D Arrays
Example
From the second element, slice elements from index 1 to index
4 (not included):
import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:4])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 148


import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 149


Data Types in NumPy
NumPy has some extra data types, and refer to data types with one character, like i
for integers, u for unsigned integers etc.
Below is a list of all data types in NumPy and the characters used to represent them.
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - 16/04/2025
fixed chunk of memory for other type ( void )
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 150
Creating Arrays With a Defined Data Type
We use the array() function to create arrays, this function can take an
optional argument: dtype that allows us to define the expected data
type of the array elements:
Example
Create an array with data type string:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 151


For i, u, f, S and U we can define size as well.
Example
Create an array with data type 4 bytes integer:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)

import numpy as np

arr = np.array(['a', '2', '3'], dtype='i')

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 152


Converting Data Type on Existing Arrays
The best way to change the data type of an existing array, is to make a copy of the
array with the astype() method.
The astype() function creates a copy of the array, and allows you to specify the data
type as a parameter.
The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or
you can use the data type directly like float for float and int for integer.
Example
Change data type from float to integer by using 'i' as parameter value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 153
import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 154


NumPy Array Copy vs View

The Difference Between Copy and View


The main difference between a copy and a view of an array is that the copy is
a new array, and the view is just a view of the original array.
The copy owns the data and any changes made to the copy will not affect
original array, and any changes made to the original array will not affect the
copy.
The view does not own the data and any changes made to the view will affect
the original array, and any changes made to the original array will affect the
view.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 155


COPY:

Example

Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 156
VIEW:
Example
Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 157


Iterating Arrays

Iterating means going through elements one by one.


As we deal with multi-dimensional arrays in numpy, we can do this
using basic for loop of python.
If we iterate on a 1-D array it will go through each element one by one.
Example
Iterate on the elements of the following 1-D array:
import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 158


Iterating 2-D Arrays

In a 2-D array it will go through all the rows.


Example
Iterate on the elements of the following 2-D array:
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

for x in arr:
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 159


Joining NumPy Arrays

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

arr = np.concatenate((arr1, arr2))

print(arr)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 160


Join two 2-D arrays along rows (axis=1):
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
arr = np.concatenate((arr1, arr2), axis=1)
print(arr)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 161


Splitting NumPy Arrays

Splitting is reverse operation of Joining.


Joining merges multiple arrays into one and Splitting breaks one array into
multiple.
We use array_split() for splitting arrays, we pass it the array we want to split
and the number of splits.
Example
Split the array in 3 parts:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 162
Splitting 2-D Arrays

Use the same syntax when splitting 2-D arrays.


Use the array_split() method, pass in the array you want to split and the
number of splits you want to do.
Example
Split the 2-D array into three 2-D arrays.
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 163
NumPy Searching Arrays

Searching Arrays
You can search an array for a certain value, and return the indexes that get a
match.
To search an array, use the where() method.
Example
Find the indexes where the value is 4:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 164


Example:
Find the indexes where the values are even:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 165


Find the indexes where the values are odd:
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

x = np.where(arr%2 == 1)

print(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 166


Sorting Arrays
Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order corresponding to
elements, like numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(), that will sort a specified
array.
Example
Sort the array:
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 167


Sorting a 2-D Array
If you use the sort() method on a 2-D array, both
arrays will be sorted:

Example
Sort a 2-D array:

import numpy as np

arr = np.array([[3, 2, 4], [5, 0, 1]])

print(np.sort(arr))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 168
Pandas

Pandas is a Python library.


Pandas is used to analyze data.
Pandas is used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python
Data Analysis" and was created by Wes McKinney in 2008.
• Why Use Pandas?
• Pandas allows us to analyze big data and make conclusions based on
statistical theories.
• Pandas can clean messy data sets, and make them readable and relevant.
• Relevant data is very important in data science.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 169
What Can Pandas Do?
Pandas gives you answers about the data. Like:
Is there a correlation between two or more columns?
What is average value?
Max value?
Min value?
Pandas are also able to delete rows that are not relevant, or contains
wrong values, like empty or NULL values. This is called cleaning the
data.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 170


• Before Pandas, Python was capable for data preparation, but it only
provided limited support for data analysis. So, Pandas came into the
picture and enhanced the capabilities of data analysis. It can perform
five significant steps required for processing and analysis of data
irrespective of the origin of the data, i.e., load, manipulate, prepare,
model, and analyze.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 171


Benefits of Pandas
• The benefits of pandas over using other language are as follows:
• Data Representation: It represents the data in a form that is suited for
data analysis through its DataFrame and Series.
• Clear code: The clear API of the Pandas allows you to focus on the
core part of the code. So, it provides clear and concise code for the
user.
Python Pandas Data Structure
• The Pandas provides two data structures for processing the data, i.e.,
Series and DataFrame, which are discussed below:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 172


Python Pandas Series
• The Pandas Series can be defined as a one-dimensional array
that is capable of storing various data types. We can easily
convert the list, tuple, and dictionary into series using "series'
method. The row labels of series are called the index. A Series
cannot contain multiple columns. It has the following
parameter:
• data: It can be any list, dictionary, or scalar value.
• index: The value of the index should be unique and hashable.
It must be of the same length as data. If we do not pass any
index, default np.arrange(n) will be used.
• dtype: It refers to the data type of series.
• copy: It is used for copying the data.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 173
Creating a Series:
We can create a Series in two ways:
• Create an empty Series
• Create a Series using inputs.
Create an Empty Series:
• We can easily create an empty series in Pandas which means it will not have any value.
• The syntax that is used for creating an Empty Series.
<series object> = pandas.Series()
• The below example creates an Empty Series type object that has no values and having
default datatype, i.e., float64.
Example
import pandas as pd
x = pd.Series()
print (x)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 174
Creating a Series using inputs:
We can create Series by using various inputs:
• Array
• Dict
• Scalar value
Creating Series from Array:
1.import pandas as pd
2.import numpy as np
3.info = np.array(['P','a','n','d','a','s'])
4.a = pd.Series(info)
5.print(a)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 175


Create a Series from dict
We can also create a Series from dict. If the dictionary object is being passed as
an input and the index is not specified, then the dictionary keys are taken in a
sorted order to construct the index.
If index is passed, then values correspond to a particular label in the index will
be extracted from the dictionary.
#import the pandas library
import pandas as pd
import numpy as np
info = {'x' : 0., 'y' : 1., 'z' : 2.}
a = pd.Series(info)
print (a)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 176


Create a Series using Scalar:
If we take the scalar values, then the index must be provided. The scalar value
will be repeated for matching the length of the index.
#import pandas library
import pandas as pd
import numpy as np
x = pd.Series(4, index=[0, 1, 2, 3])
print (x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 177


Accessing data from series with Position:
Once you create the Series type object, you can access its indexes, data, and
even individual elements.
The data in the Series can be accessed similar to that in the ndarray.
import pandas as pd
x = pd.Series([1,2,3],index = ['a',’ b','c’])
print (x)
#retrieve the first element
print (x[0])

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 178


Series object attributes
• The Series attribute is defined as any information related to
the Series object such as size, datatype. etc. Below are some
of the attributes that you can use to get the information about
the Series object:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 179


Attributes Description
Series.index Defines the index of the Series.
Series.shape It returns a tuple of shape of the data.

Series.dtype It returns the data type of the data.


Series.size It returns the size of the data.
Series.empty It returns True if Series object is empty, otherwise returns false.
Series.hasnans It returns True if there are any NaN values, otherwise returns false.
Series.nbytes It returns the number of bytes in the data.
Series.ndim It returns the number of dimensions in the data.
Series.itemsize It returns the size of the datatype of item.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 180


Checking Emptiness and Presence of NaNs
• To check the Series object is empty, you can use the empty
attribute. Similarly, to check if a series object contains some NaN
values or not, you can use the hasans attribute.
Example
1.import numpy as np
2.import pandas as pd
3.a=pd.Series(data=[1,2,3,np.NaN])
4.b=pd.Series(data=[4.9,8.2,5.6],index=['x','y','z'])
5.c=pd.Series()
6.print(a.empty,b.empty,c.empty)
7.print(a.hasnans,b.hasnans,c.hasnans)
8.print(len(a),len(b))
9.print(a.count( ),b.count( ))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 181
Series Functions

There are some functions used in Series which are as follows:

Functions Description
Pandas Series.map() Map the values from two series that have a common
column.
Pandas Series.std() Calculate the standard deviation of the given set of
numbers, DataFrame, column, and rows.

Pandas Series.to_frame() Convert the series object to the dataframe.

Pandas Series.value_count Returns a Series that contain counts of unique values.


s()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 182


• Pandas Series.map()
• The main task of map() is used to map the values from two series that
have a common column. To map the two Series, the last column of the
first Series should be the same as the index column of the second
series, and the values should be unique.
• Syntax: Series.map(arg, na_action=None)
• Parameter
• arg:function,dict,orSeries.
It refers to the mapping correspondence.
na_action: {None, 'ignore'}, Default
value None.
If ignore, it returns null values, without
passing it
to the mapping correspondence.
• Returns
It returns
16/04/2025
the Pandas Series with the same index as a caller.
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 183
Example

1.import pandas as pd
2.import numpy as np
3.a = pd.Series(['Java', 'C', 'C++', np.nan])
4.a.map({'Java': 'Core'})

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 184


Example2

1.import pandas as pd
2.import numpy as np
3.a = pd.Series(['Java', 'C', 'C++', np.nan])
4.a.map({'Java': 'Core'})
5.a.map('I like {}'.format, na_action='ignore')

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 185


• Pandas Series.std()
• The Pandas std() is defined as a function for calculating the
standard deviation of the given set of numbers, DataFrame,
column, and rows. In respect to calculate the standard
deviation, we need to import the package named "statistics"
for the calculation of median.
• The standard deviation is normalized by N-1 by default and
can be changed using the ddof argument.
• Syntax:
1.Series.std(axis=None, skipna=None, level=None, ddof=1, nu
meric_only=None, **kwargs)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 186


• Parameters:
• axis: {index (0), columns (1)}
• skipna: It excludes all the NA/null values. If NA is present in
an entire row/column, the result will be NA.
• level: It counts along with a particular level, and collapsing
into a scalar if the axis is a MultiIndex (hierarchical).
• ddof: Delta Degrees of Freedom. The divisor used in
calculations is N - ddof, where N represents the number of
elements.
• numeric_only: boolean, default value None
It includes only float, int, boolean columns. If it is None, it will
attempt to use everything, so use only numeric data.
• It is not implemented for a Series.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 187
import pandas as pd
1.# calculate standard deviation
2.import numpy as np
3.print(np.std([4,7,2,1,6,3]))
4.print(np.std([6,9,15,2,-17,15,4]))

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 188


DataFrame
• Pandas DataFrame is two-dimensional size-mutable,
potentially heterogeneous tabular data structure with labeled
axes (rows and columns).
• A Data frame is a two-dimensional data structure, i.e., data is
aligned in a tabular fashion in rows and columns.
• A Pandas DataFrame is a 2 dimensional data structure, like a 2
dimensional array, or a table with rows and columns.
• Pandas DataFrame consists of three principal components,
the data, rows, and columns.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 189


16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 190
Creating a Pandas DataFrame

• In the real world, a Pandas DataFrame will be created by loading the datasets
from existing storage, storage can be SQL Database, CSV file, and Excel file.
Pandas DataFrame can be created from the lists, dictionary, and from a list of
dictionary etc. Dataframe can be created in different ways here are some
ways by which we create a dataframe:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 191


• import pandas as pd

DWDMMarks = {
"Minor-1": [10, 9, 8],
"MSE-1": [26, 25, 24]
}

#load data into a DataFrame object:

df = pd.DataFrame(DWDMMarks)

print(df)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 192


• Named Indexes
• With the index argument, you can name your own indexes.
• Example
import pandas as pd

DWDMMarks = {
"Minor-1": [10, 9, 8],
"MSE-1": [36, 35, 34]
}

#load data into a DataFrame object:

df = pd.DataFrame(DWDMMarks,index = ["Top1marks", "Top2marks", "Top3


marks"])

print(df)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 193
Create a DataFrame using List

• We can easily create a DataFrame in Pandas using list.


1.# importing the pandas library
2.import pandas as pd
3.# a list of strings
4.x = ['Python', 'Pandas']
5.# Calling DataFrame constructor on list
6.df = pd.DataFrame(x)
7.print(df)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 194


Example:2
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)

Example:3

import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df =pd.DataFrame(data,columns=['Name','Age'],dtype=float)
Print(df)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 195
Create a DataFrame from List of Dicts
• List of Dictionaries can be passed as input data to create a DataFrame. The
dictionary keys are by default taken as column names.
Example 1
The following example shows how to create a DataFrame by passing a list of
dictionaries.
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print (df)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 196


Creating a DataFrame using Excel file

• Read an excel file using read_excel() method of pandas.

import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
print(df)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 197


Reading Specific Sheets using ‘sheet_name’ of
read_excel() method

import pandas as pd
df = pd.read_excel('MyExcel.xlsx', sheet_name=1)
print(df)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 198


• Reading Specific Columns using ‘usecols’ parameter of read_excel() method.

# import pandas lib as pd


import pandas as pd

require_cols = [0,3]

# only read specific columns from an excel file


required_df = pd.read_excel('MyExcel.xlsx', usecols = require_cols
)

print(required_df)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 199


Pandas - Cleaning Empty Cells.
Empty cells can potentially give you a wrong result when you
analyze data.

Remove Rows
One way to deal with empty cells is to remove rows that
contain empty cells.

import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
new_df = df.dropna()
print(new_df.to_string())

Note: By default, the dropna() method returns a new DataFrame, and will not change the original.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 200


Replace Empty Values
Another way of dealing with empty cells is to insert a new value instead.
This way you do not have to delete entire rows just because of some
empty cells.
The fillna() method allows us to replace empty cells with a value:
Example
Replace NULL values with the number 130:

import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
new_df = df.dropna()
print(new_df.to_string())

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 201


Replace Only For Specified Columns

The example above replaces all empty cells in


the whole Data Frame.

To only replace empty values for one column,


specify the column name for the DataFrame:

import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
df["Rollno"].fillna(9999)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 202


import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
x = df["ROLLNO"].mean()
x = df["ROLLNO"].median()

df["ROLLNO"].fillna(x)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 203


• import pandas as pd
• df = pd.read_csv('data.csv')
• print(df.duplicated())

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 204


Data visualization
• Data visualization is the discipline of trying to understand data by placing it in
a visual context so that patterns, trends and correlations that might not
otherwise be detected can be exposed.
• Python offers multiple great graphing libraries that come packed with lots of
different features. No matter if you want to create interactive, live or highly
customized plots python has an excellent library for you.
• The following are few popular plotting libraries in python:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 205


Matplotlib

• Matplotlib is a low level graph plotting library in python that serves as a


visualization utility.
• Matplotlib was created by John D. Hunter.
• Matplotlib is open source and we can use it freely.
• Matplotlib is mostly written in python, a few segments are written in C,
Objective-C and Javascript for Platform compatibility.

16/04/2025 Mr. N. Rajender, Asst. Prof, Dept of IT,KITSW 206


Matplotlib Pyplot
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Example
Draw a line in a diagram from position (0,0) to position (6,25):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 25])
plt.plot(xpoints, ypoints)
plt.show()
16/04/2025 Mr. N .Rajender, Asst.Prof, Dept of IT,KITSW 207
• If we need to plot a line from (1, 3) to (8, 10).
• we have to pass two arrays [1, 8] and [3, 10] to the plot function.

Plotting Without Line


To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'.

Example
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 208
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6,
1) and finally to position (8, 10):

Default X-Points
If we do not specify the points in the x-axis, they will get the default values 0, 1,
2, 3, etc. depending on the length of the y-points.

Markers
You can use the keyword argument marker to emphasize each point with a
specified marker:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 209


• Marker Description
• 'o’ Circle
• '*’ Star
• '.’ Point
• ',’ Pixel
• 'x’ X
• 'X’ X (filled)
• '+’ Plus
• 'P’ Plus (filled)
• 's’ Square
• 'D’ Diamond
• 'd’ Diamond (thin)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 210
• 'p’ Pentagon
• 'H’ Hexagon
• 'h’ Hexagon
• 'v’ Triangle Down
• '^’ Triangle Up
• '<‘ Triangle Left
• '>’ Triangle Right
• '1’ Tri Down
• '2’ Tri Up
• '3’ Tri Left
• '4’ Tri Right
• '|’ Vline
• '_’ Hline
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 211
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, 'o:g')
plt.show()

Line Reference
Line Syntax Description
'-’ Solid line
':’ Dotted line
'--’ Dashed line
'-.’ Dashed/dotted line

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 212


Color Reference
Color Syntax Description
'r’ Red
'g’ Green
'b’ Blue
'c’ Cyan
'm’ Magenta
'y’ Yellow
'k’ Black
'w’ White

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 213


import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o', ms = 20)
plt.show()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 214


import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20, mec


= 'r')
plt.show()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 215


import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20, mfc


= 'r')
plt.show()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 216


Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style
of the plotted line:
Example
Use a dotted line:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 217


Line Styles
You can choose any of these styles:

Style Or
'solid' (default) '-'
'dotted’ ':'
'dashed’ '--'
'dashdot’ '-.'
'None’ '' or ' '

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 218


• import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, color = 'r')


plt.show()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 219


plt.title("Sports Watch Data", loc = 'left')
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 220


plt.grid()
plt.grid(axis = 'x’)
plt.grid(axis = 'y’)
plt.grid(color = 'green', linestyle = '--', linewidth
= 0.5)

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 221


Matplotlib Subplot
• import matplotlib.pyplot as plt
import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)

plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 222
The subplot() Function
The subplot() function takes three arguments that describes the layout of the
figure.
The layout is organized in rows and columns, which are represented by the
first and second argument.
The third argument represents the index of the current plot.
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.

Note:-You can draw as many plots you like on one figure, just describe the
number of rows, columns, and the index of the plot.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 223
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 224
import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 1)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 3, 2)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 3)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 3, 4)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 5)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 3, 6)
plt.plot(x,y)

plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 225
Title
You can add a title to each plot with the title() function:
plt.title("SALES").
Super Title
You can add a title to the entire figure with the suptitle() function:

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 226


Creating Scatter Plots
With Pyplot, you can use the scatter() function to draw a scatter plot.

The scatter() function plots one dot for each observation.


It needs two arrays of the same length, one for the values of the x-axis, and one for values
on the y-axis:
Example
A simple scatter plot:
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

plt.scatter(x, y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 227
Color Each Dot
You can even set a specific color for each dot by using an array of colors as value for the c argument:

Note: You cannot use the color argument for this, only the c argument.

Example
Set your own color of the markers:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors =
np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])

plt.scatter(x, y, c=colors)

plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 228
Matplotlib Bars
Creating Bars
With Pyplot, we can use the bar() function to draw bar graphs:

Example
Draw 4 bars:

import matplotlib.pyplot as plt


import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 229
The bar() function takes arguments that describes the
layout of the bars.

The categories and their values represented by the


first and second argument as arrays

import matplotlib.pyplot as plt


import numpy as np
x = ["it", "cse"]
y = [66, 198]
plt.bar(x, y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 230
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use the barh() function:

Example
Draw 4 horizontal bars:

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 231
Bar Color
The bar() and barh() takes the keyword argument
color to set the color of the bars:

import matplotlib.pyplot as plt


import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, color = "green")
plt.show()

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 232


Bar Width
The bar() takes the keyword argument width to set the
width of the bars:

import matplotlib.pyplot as plt


import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, width = 0.2)
plt.show()
The default width value is 0.8
Note: For horizontal bars, use height instead of width.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 233
Matplotlib Pie Charts
Creating Pie Charts
With Pyplot, you can use the pie() function to draw pie charts:

Example
A simple pie chart:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


plt.pie(y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 234
Plotting Data distributions, Categorical and Time-Series data
Data Distribution
In the real world, the data sets are much bigger, but it can be difficult to
gather real world data, at least at an early stage of a project.
How Can we Get Big Data Sets?
To create big data sets for testing, we use the Python module NumPy,
which comes with a number of methods to create random data sets, of
any size.
Histogram
To visualize the data set we can draw a histogram with the data we
collected. We will use the
Python module Matplotlib to draw a histogram.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 235


Normal Data Distribution
In probability theory this kind of data distribution is known as the normal data
distribution, or the Gaussian data distribution, after the mathematician Carl
Friedrich Gauss who came up with the formula of this data distribution.

What is a Time Series?


Time series is a sequence of observations recorded at regular time intervals.
Depending on the frequency of observations, a time series may typically be
hourly, daily, weekly, monthly, quarterly and annual. Sometimes, you might
have seconds and minute-wise time series as well, like, number of clicks and
user visits every minute etc

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 236


What is a Categorical data?

Categorical features can only take on a limited, and usually fixed, number of
possible values. For example, if a dataset is about information related to
users, then you will typically find features like country, gender, age group,
etc. Alternatively, if the data you're working with is related to products, you
will find features like product type, manufacturer, seller and so on.

These are all categorical features in your dataset. These features are
typically stored as text values which represent various traits of the
observations. For example, gender is described as Male (M) or Female (F),
product type could be described as electronics, apparels, food etc.

16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 237


import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
x=np.array([1,10,20,40,50,70])
y=np.array([3,20,90,110,130,170])
linreg=LinearRegression()
x=x.reshape(-1,1)
linreg.fit(x,y)
y_pred=linreg.predict(x)
plt.scatter(x,y,color='magenta')
plt.plot(x,y_pred,color="green")
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 238

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy