0% found this document useful (0 votes)
81 views

Python Lab Manual

Uploaded by

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

Python Lab Manual

Uploaded by

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

SRK INSTITUTE OF TECHNOLOGY

Enikepadu, Vijayawada 521108


Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

L T P C
0 1 2 2

PYTHON PROGRAMMING
Course Objectives:

The main objectives of the course are to

a. Introduce core programming concepts of Python programming language.


b. Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries
c. Implement Functions, Modules and Regular Expressions in Python Programming
and to create practical and contemporary applications using these

Course Outcomes:
Upon successful completion of the course, the student will be able to:
 Apply Python's fundamental components, construct control flow statements, perform
input/output operations, manage exceptions, and develop well-structured, efficient, and
robust Python programs.
 Apply functions and their arguments, manage variable scope and lifetime, handle
command line arguments, manipulate strings and lists using various operations and
methods, and utilize built-in functions and commonly used modules to develop efficient
Python programs.
 Apply built-in functions and methods on dictionaries, tuples, and sets, utilize tuples and
sets for efficient data handling.
 Utilize file methods and modules to perform file operations, define and apply object-
oriented programming principles by developing classes and objects, and implement
encapsulation, inheritance, and polymorphism to construct robust and maintainable
Python programs.
 Apply functional programming principles, work with JSON and XML data formats,
utilize NumPy for numerical computations, and manipulate data efficiently using Pandas
to perform data science tasks and analyses effectively.

Mapping of CO’s & PO’s


CO/PO PO1 PO2 PSO1 PSO
2
CO1
CO2
CO3
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

S.No Name of the Experiment Remarks


1: 1. i)Write a program to find the largest element among
three Numbers.
Parts of ii)Write a Program to display all prime numbers within
an interval
Python
iii)Write a program to swap two numbers without
Programming using a temporary variable.
Language 2. Demonstrate the following Operators in Python with
suitable examples.
i) Arithmetic Operators ii) Relational Operators iii)
Control Flow Assignment Operatorsiv) Logical Operators v) Bit
Statements wise Operators vi) Ternary Operator vii)
Membership Operators
viii) Identity Operators
3. i)Write a program to add and multiply complex
numbers
ii)Write a program to print multiplication table of a
given number.

2: 4. i)Write a program to define a function with multiple


Functions return values.
ii)Write a program to define a function using default
arguments.
Strings
5. i)Write a program to find the length of the string
without using any library functions.
Lists ii)Write a program to check if the substring is present
in a given string or not.
6. Write a program to perform the given operations on a
list:
i) Addition ii. Insertion iii. slicing
7. Write a program to perform any 5 built-in functions by
taking any list.

3:
Dictionaries
8. i)Write a program to create tuples (name, age,
address, college) for at least two members and
Tuples
concatenate the tuples and print the concatenated
tuples.
Sets ii)Write a program to count the number of vowels in a
string (No control flow allowed).
iii)Write a program to check if a given key exists in a
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

dictionary or not.
9. i)Write a program to add a new key-value pair to an
existing dictionary.
ii)Write a program to sum all the items in a given
dictionary.

4:

10.
i) Write a program to sort words in a file and put them
Files
in another file. The output file should have only
lower-case words, so any upper-case words from
OOPS source must be lowered.
ii) Python program to print each line of a file in reverse
order.
iii) Python program to compute the number of characters,
words and lines in a file.
11.
i) Write a program to create, display, append,
insert and reverse the order of the items in the
array.
ii) Write a program to add, transpose and multiply two
matrices.
iii) Write a Python program to create a class that
represents a shape. Include methods to calculate its area
and perimeter. Implement subclasses for different
shapes like circle, triangle, and square.

5: 12. Python program to check whether a JSON string


contains complex object or not.
JSON 13. i) Python Program to demonstrate NumPy arrays
creation using array () function.
ii) Python program to demonstrate use of ndim, shape,
XML size, dtype.
iii) Python program to demonstrate basic slicing,
integer and Boolean indexing.
Numpy iv) Python program to find min, max, sum, cumulative
sum of array
Pandas 14. Create a dictionary with at least five keys and each
key represent value as a list where this list contains
at least ten values and convert this dictionary as a
pandas data frame and explore the data through the
data frame as follows:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

i) Apply head () function to the pandas data frame


ii) Perform various data selection operations on Data
Frame
15. Select any two columns from the above data frame,
and observe the change in one attribute with respect
to other attribute with scatter and plot operations in
matplotlib

Text Books/ Reference Books:


1. Gowrishankar S, Veena A., Introduction to Python Programming, CRC Press.
2. Python Programming, S Sridhar, J Indumathi, V M Hariharan, 2ndEdition, Pearson,
2024
3. Introduction to Programming Using Python, Y. Daniel Liang, Pearson.

Online Learning Resources/Virtual Labs:


1. https://www.coursera.org/learn/python-for-applied-data-science-ai
2. https://www.coursera.org/learn/python?specialization=python#syllabus
3. https://www.w3schools.com/python/python_reference.asp
4. https://www.python.org/doc/

Preface

This Lab manual introduces the python programming language. It focusses on the beginners
to learn python programming at ease. Python is a popular programming language based on
object oriented programming concepts. It was created by Guido van Rossum, and released in
1991. Its simple and easy syntax helps students to learn the language easily and this manual
aims at helping the Engineering students to understand the course and its objectives and cover
all the applied aspects of the course syllabus. The manual is based on five parts from basic
programming, syntax, identifiers, control flow staterments , loops , functions , lists,
dictionaries, tuples, sets , to files, oops concepts, JSON, XML, Numpy and Pandas.

Python Programming Introduction:


Python is an interpreted, object-oriented, high-level programming language with dynamic
semantics. Python is used for server-side web development, software development,
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

mathematics, and system scripting, and is popular for Rapid Application Development and as
a scripting or glue language to tie existing components because of its high-level, built-in data
structures, dynamic typing, and dynamic binding. Program maintenance costs are reduced
with Python due to the easily learned syntax and emphasis on readability.
Features and Benefits of Python
 Compatible with a variety of platforms including Windows, Mac, Linux, Raspberry
Pi, and others
 Uses a simple syntax comparable to the English language that lets developers use
fewer lines than other programming languages
 Operates on an interpreter system that allows code to be executed immediately, fast-
tracking prototyping
 Can be handled in a procedural, object-orientated, or functional way

Python Syntax
 Somewhat similar to the English language, with a mathematical influence, Python is
built for readability
 Unlike other languages that use semicolons and/or parentheses to complete a
command, Python uses new lines for the same function
 Defines scope (i.e., loops, functions, classes) by relying indentation, using
whitespace, rather than braces (aka curly brackets)

Python Flexibility
Python, a dynamically typed language, is especially flexible, eliminating hard rules for
building features and offering more problem-solving flexibility with a variety of methods. It
also allows uses to compile and run programs right up to a problematic area because it uses
run-time type checking rather than compile-time checking.

The Less Great Parts of Python


On the down side, Python isn’t easy to maintain. One command can have multiple meanings
depending on context because Python is a dynamically typed language. And, maintaining a
Python app as it grows in size and complexity can be increasingly difficult, especially finding
and fixing errors. Users will need experience to design code or write unit tests that make
maintenance easier.
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Speed is another weakness in Python. Its flexibility, because it is dynamically typed, requires
a significant amount of referencing to land on a correct definition, slowing performance. This
can be mitigated by using alternative implementation of Python (e.g. PyPy).

Python and AI
AI researchers are fans of Python. Google TensorFlow, as well as other libraries (scikit-learn,
Keras), establish a foundation for AI development because of the usability and flexibility it
offers Python users. These libraries, and their availability, are critical because they enable
developers to focus on growth and building.

Part 1 Covers:
History of Python Programming Language, Thrust Areas of Python, Installing Anaconda
Python Distribution, Installing and Using Jupyter Notebook.
Parts of Python Programming Language: Identifiers, Keywords, Statements and
Expressions, Variables, Operators, Precedence and Associativity, Data Types, Indentation,
Comments, Reading Input, Print Output, Type Conversions, the type () Function and Is
Operator, Dynamic and Strongly Typed Language.
Control Flow Statements: if statement, if-else statement, if...elif…else, Nested if statement,
while Loop, for Loop, continue and break Statements, Catching Exceptions Using try and
except Statement.

Installation :
1) install python (3.4 above version , pip is default )
2) install pip ( for <=3.4 versions)

To check to see if python is installed.

In cmd prompt

C:\Users\hp> python
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] ::
Anaconda, Inc. on win32

To check to see if pip is installed.

In cmd prompt

C:\Users\hp> python -m pip –version

Once installed and checked in the command prompt, open a notepad, write the program and
save as “filename”.py and save it.

To run the file:


Cmd>
Python filename.py

Experiment 1:

1. i) Write a program to find the largest element among three Numbers.

# Python program to find the largest element among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

elif (num2 >= num1) and (num2 >= num3):


largest = num2
else:
largest = num3

print("The largest element is", largest)

Observation: The three numbers are stored in num1, num2 and num3 respectively. We've used
the if...elif...else ladder to find the largest among the three and display it. It introduces variables,
expressions, datatypes(float) and inputting values

Output:
The largest number is 14

Using User input:


Enter first number: 10
Enter second number: 20
Enter third number: 30
The largest number is 30.0

1. ii)Write a Program to display all prime numbers within an interval.


2. # Python program to display all the prime numbers within an interval
3.
4. lower = 900
5. upper = 1000
6.
7. print("Prime numbers between", lower, "and", upper, "are:")
8.
9. for num in range(lower, upper + 1):
10. # all prime numbers are greater than 1
11. if num > 1:
12. for i in range(2, num):
13. if (num % i) == 0:
14. break
15. else:
16. print(num)
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Observation: Using for loops, break, lower and upper functions and keywords

Output:

Prime numbers between 900 and 1000 are:


907
911
919
929
937
941
947
953
967
971
977
983
991
997

1. iii)Write a program to swap two numbers without using a temporary variable.


For Example:
X : 10
Y : 20

After swapping X and Y, we get :

X : 20
Y : 10

# Python code to swap two numbers


# without using another variable

x=5
y=7
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

print ("Before swapping: ")


print("Value of x : ", x, " and y : ", y)

# code to swap 'x' and 'y'


x, y = y, x

print ("After swapping: ")


print("Value of x : ", x, " and y : ", y)

Output:
Before swapping:
Value of x : 5 and y : 7
After swapping:
Value of x : 7 and y : 5

Note: The same program can also be done using a Bitwise XOR function

# Python code to swap two numbers


# using Bitwise XOR method

x = 5 # x = 0101
y = 10 # y = 1010

print ("Before swapping: ")


print("Value of x : ", x, " and y : ", y)

# Swap code
x ^= y # x = 1111, y = 1010
y ^= x # y = 0101, x = 1111
x ^= y # x = 1010, y = 0101

print ("After swapping: ")


print("Value of x : ", x, " and y : ", y)
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
`
Experiment 2

Demonstrate the following Operators in Python with suitable examples.


i) Arithmetic Operators ii) Relational Operators iii) Assignment Operatorsiv) Logical
Operators v) Bit wise Operators vi) Ternary Operator vii) Membership Operators
viii) Identity Operators

i) Arithmetic Operators:

#Program to input two numbers and performing all arithmetic operations


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

#Input first number


num1 = int(input("Enter first number: "))
#Input Second number
num2 = int(input("Enter second number: "))

#Printing the result for all arithmetic operations


print("Results:-")
print("Addition: ",num1+num2)
print("Subtraction: ",num1-num2)
print("Multiplication: ",num1*num2)
print("Division: ",num1/num2)
print("Modulus: ", num1%num2)
print("Floor Division: ",num1//num2)
print("Exponentiation: ",num1 ** num2)

OUTPUT:
Enter first number: 8
Enter second number: 3
Results:-
Addition: 11
Subtraction: 5
Multiplication: 24
Division: 2.6666666666666665
Modulus: 2
Floor Division: 2
Exponentiation: 512
ii) Bitwise operators:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

a = 10
b=4

# Print bitwise AND operation


print("a & b =", a & b)
# Print bitwise OR operation
print("a | b =", a | b)
# print bitwise XOR operation
print("a ^ b =", a ^ b)
# Print bitwise NOT operation
print("~a =", ~a)
a = 10
b = -10
# print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
a=5
b = -10
# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)

output:
a&b=0
a | b = 14
a ^ b = 14
~a = -11
a >> 1 = 5
b >> 1 = -5
a << 1 = 10
b << 1 = -20

iii) Ternanry Operators:

Ternary Operator determines if a condition is true or false and then returns the
appropriate value as the result. The ternary operator is useful in cases where we need to
assign a value to a variable based on a simple condition, and we want to keep our code
more concise — all in just one line of code.
Syntax: true_value if condition else false_value

# Program to demonstrate ternary operator


a = 10
b = 20

# python ternary operator


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

min = "a is minimum" if a < b else "b is minimum"

print(min)

output:
a is minimum

Ternary Operator in Nested If else

The ternary operator can also be used in Python nested if-else statement . the syntax for the same is
as follows:
Syntax: true_value if condition1 else (true_value if condition2 else false_value)
# Python program to demonstrate nested ternary operator
a = 10
b = 20

print("Both are equal" if a == b else "a is greater"


if a > b else "b is greater")

output:
b is greater

iv) Membership operators:


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

v) 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:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

#Program to demonstrate membership operators and identity operators


print("Membership operators:")
#in
x = "Hello, World!"
print("ello" in x) #Returns true as it exists
print("hello" in x) #Returns false as 'h' is in lowercase
print("World" in x)#Returns true as it exists

#not in
x = "Hello, World!"
print("ello" not in x) #Returns false as it exists
print("hello" not in x) #Returns true as it does not exist
print("World" not in x) #Returns false as it exists

print("Identity operators:")
#identity operators is and not is
x = ["bread", "cake"]
y = ["bread", "cake"]
z=x

#is
print(x is z)
#This returns true as x has been assigned to z, therefore, z and x points to the same object.

print(type(x) is list)
#This returns true as x is indeed a list object.

#Note that is is not the same as == (equals to)

#is not
print(x is not y)
#This returns true as x and y are not the same objects even though they have the same
#content.
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

print(type(z) is not list)


#This returns false as z is indeed list x.

Output:
Membership operators:
True
False
True
False
True
False
Identity operators:
True
True
True
False

Experiment 3:
i)Write a program to add and multiply complex numbers

# Python program to add two complex numbers


# function that returns a complex number after adding

def addComplex( z1, z2):


return z1 + z2

# Driver's code
z1 = complex(2, 3)
z2 = complex(1, 2)
print( "Addition is : ", addComplex(z1, z2))

# Python program to demonstrate multiplication of complex numbers

def mulComplex( z1, z2):


return z1*z2
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

# driver code
z1 = complex(2, 3)
z2 = complex(4, 5)

print("Multiplication is :", mulComplex(z1,z2))

Output:

Addition is : (3+5j)
Multiplication is : (-7+22j)

3 ii)Write a program to print multiplication table of a given number.

# Multiplication table (from 1 to 10) in Python

num = 12

# To take input from the user


# num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)

Output:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

Output:
Display multiplication table of? 10
10 x 1 = 10
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 10 = 100
Part 2 covers the below topics
Functions: Built-In Functions, Commonly Used Modules, Function Definition and Calling
the function, return Statement and void Function, Scope and Lifetime of Variables, Default
Parameters, Keyword Arguments, *args and **kwargs, Command Line Arguments. Strings:
Creating and Storing Strings, Basic String Operations, Accessing Characters in String by
Index Number, String Slicing and Joining, String Methods, Formatting Strings.
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In Functions
Used on Lists, List Methods, del Statement.

Experiment 4:
i)Write a program to define a function with multiple return values.

Output:
('John', 'Armin')
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

John Armin
ii)Write a program to define a function using default arguments.

Output:
Sum: 5
Sum: 5
Sum: 10
Sum: 15
5 i)Write a program to find the length of the string without using any library functions.
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:
Enter string:Hi This is a sample test
Length of the string is:
25
ii)Write a program to check if the substring is present in a given string or not.

Output1:
Enter string:I am a string
Enter word:string
Substring in string!

Output2:
Enter string:I am a string
Enter word:python
Substring not found in string!

6 Write a program to perform the given operations on a list:


a. Addition ii. Insertion iii. Slicing
i)adding to the list
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:
[0, 2, 4, 6, 8]
b. Inserting into list

Output:
0
2
4
6
8
After inserting:
0
2
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

4
6
8
12

c. Slicing using a list

Output
['I', 'have', ['now', 'learned', 'how'], 'to', 'Slice', '!']
7 Write a program to perform any 5 built-in functions by taking any list.

The following below are built in functions & methods available in python:

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

ascii() Returns a readable version of an object. Replaces none-ascii characters


with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the specified
object

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is divided by
argument2

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object

eval() Evaluates and executes an expression

exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or method)

globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute
(property/method)
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current local symbol table

map() Returns the specified iterator with the specified function applied to
each item

max() Returns the largest item in an iterable

memoryview() Returns a memory view object

min() Returns the smallest item in an iterable

next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of the specified character


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increments by 1


(by default)

repr() Returns a readable version of an object

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list

staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

super() Returns an object that represents the parent class

tuple() Returns a tuple

type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of
where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of
where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified


value

rfind() Searches the string for a specified value and returns the last position of
where it was found

rindex() Searches the string for a specified value and returns the last position of
where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

zfill() Fills the string with a specified number of 0 values at the beginning
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:

Absolute value of -40 is: 20


Absolute value of 3+4j is: 5.0
The key will display: False
The key displays True
length of: PALINDROME
10
length of: ('a', 'e', 'i', 'o', 'u')
5
length of: ['1', '2', '3', 'o', '10u']
5
bin values for 4 & 9 are:
0b100
0b1001

Experiment 3
Creating Dictionary, Accessing and Modifying key: value Pairs in Dictionaries, Built-In
Functions Used on Dictionaries, Dictionary Methods, del Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple() Function, Indexing and
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Slicing in Tuples, Built-In Functions Used on Tuples, Relation between Tuples and Lists,
Relation between Tuples and Dictionaries, Using zip() Function, Sets, Set Methods,
Frozenset.

8. i)Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.

Output:

The original tuple 1 (name, age, address, college): ('Mahimna', 18, 'BloomField villa
8,RK Street, T.Nagar,Chennai', 'DPS College')
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

The original tuple 2 (name, age, address, college): ('Maraali', 19, 'SLV Green
Meadows,Villa 200, Ramavarappadu, Vijaywada', 'SRKIT College')

The original tuple 3 (name, age, address, college): ('Mahathi', 24, 'MyHome Ankura, Flat
304, TN colony, Attapur, Hyderabad', 'KLU Hyd')

The tuple after concatenation is : ('Mahimna', 18, 'BloomField villa 8,RK Street,
T.Nagar,Chennai', 'DPS College', 'Maraali', 19, 'SLV Green Meadows,Villa 200,
Ramavarappadu, Vijaywada', 'SRKIT College', 'Mahathi', 24, 'MyHome Ankura, Flat 304,
TN colony, Attapur, Hyderabad', 'KLU Hyd')

ii)Write a program to count the number of vowels in a string using Sets.

The control flow statements in Python are :


Control statements direct the flow of a Python program's execution. They introduce logic, decision-
making, and looping. Key control statements in Python include if/else, for/while, break/continue, and
pass.
// program to count the number of vowels in a string
// The below program is using frozenset() datatype

Set is a data type in python used to store several items in a single variable. It is one of the four built-in
data types (List, Dictionary, Tuple, and Set) having qualities and usage different from the other three.
It is a collection that is written with curly brackets and is both unindexed and unordered
frozenSet: Set is mutable while frozenset is immutable. This means that we can add or remove
elements from a set, but not from a frozenset. Memory usage: Since set is mutable, it requires more
memory to store the elements as compared to frozenset, which is immutable and requires less memory
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:
Enter string:A Friend in NEED is a FRIEND indeed
Count of the vowels is:
13
Enter string:A friend IN need IS A Friend INDEED
Count of the vowels without Control flow is:
13

iii)Write a program to check if a given key exists in a dictionary or not.

Python dictionary can not contain duplicate keys so it is very crucial to check if a key is
already present in the dictionary. If you accidentally assign a duplicate key value, the new
value will overwrite the old one.
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

So in a given dictionary, our task is to check if the given key already exists in a dictionary or
not. If present, print “present” and the value of the key. Otherwise, print “Not present”.

Output:
Present, value = 200
Not present

9
\i)Write a program to add a new key-value pair to an existing dictionary.
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:

9
ii)Write a program to sum all the items in a given dictionary.

Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary.
Examples:
Input : {‘a’: 100, ‘b’:200, ‘c’:300}
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output : 600

Output:

UNIT-IV: Files: Types of Files, Creating and Reading Text Data, File Methods to Read and
Write Data, Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV
Files, Python os and os.path Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python, Creating
Objects in Python, Constructor Method, Classes with Multiple Objects, Class Attributes Vs
Data Attributes, Encapsulation, Inheritance, Polymorphism.

Python provides inbuilt functions for creating, writing, and reading files. Two types of files
can be handled in python, normal text files and binary files (written in binary language,0s,
and 1s).
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

 Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.
 Binary files: In this type of file, there is no terminator for a line, and the data is stored
after converting it into machine-understandable binary language.
Approach:
There are two approaches to do so:
 Using loops to read and copy content from one file to another.
 Using file methods to read and copy content from one file to another.
Input File:
Method 1: Using loops
Approach:
 Opening the input file in the read mode.
 Opening the output file in the write mode.
 Read lines from the input file and write it in the output file.
Below is the implementation of the above approach:

let’s see the definition of some important functions which will be used:
 open() – It is used to open a file in various modes like reading, write, append, both
read and write.
 write() – It is used to write a specified text to a file.
 upper() – It is used to convert all the lowercase letters to uppercase letters of a string
and finally returns it.
Method 1: Using file handling to read and write
In this method, we would be using ‘r’ mode(to read the file) in the first file and ‘w’ mode(to
write in a file) in the second file. Finally, we will write the content of the first file into the
second file by using the write method. We will use the upper method there to capitalize the
content while writing the content into the second file.
FILES
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

10
i) Write a program to sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper-case words from source must be
lowered.

The file “all_words.txt” is as below:


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

FILES
10 ii) Python program to print each line of a file in reverse order.

The below code is for full_reverse, that’s is the word is reversed and the lines are also
reversed
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

The below code reverses each line


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

10 iii) Python program to compute the number of characters, words and lines in a file.
Get the number of characters, words, spaces, and lines in a file

 The naive approach of getting the number of characters, words, spaces, and lines in a
file.

 Using some built-in functions and OS module functions

Count the Number of Lines, Words, and Characters using the Native Method
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

In this approach, the idea is to solve the task by developing our own logic. Without using any
built-in function of Python, the total number of characters, words, spaces and lines of the
file will be calculated. Below is the implementation of the above approach.

# Function to count number of characters, words, spaces and lines in a file

def counter(fname):

# variable to store total word count

num_words = 0

# variable to store total line count

num_lines = 0

# variable to store total character count

num_charc = 0

# variable to store total space count

num_spaces = 0

# opening file using with() method

# so that file gets closed

# after completion of work

with open(fname, 'r') as f:

# loop to iterate file

# line by line
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

for line in f:

# incrementing value of num_lines with each

# iteration of loop to store total line count

num_lines += 1

# declaring a variable word and assigning its value as Y

# because every file is supposed to start with a word or a character

word = 'Y'

# loop to iterate every

# line letter by letter

for letter in line:

# condition to check that the encountered character

# is not white space and a word

if (letter != ' ' and word == 'Y'):

# incrementing the word

# count by 1

num_words += 1

# assigning value N to variable word because until

# space will not encounter a word can not be


completed
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

word = 'N'

# condition to check that the encountered character is a white


space

elif (letter == ' '):

# incrementing the space

# count by 1

num_spaces += 1

# assigning value Y to variable word because after

# white space a word is supposed to occur

word = 'Y'

# loop to iterate every character

for i in letter:

# condition to check white space

if(i !=" " and i !="\n"):

# incrementing character

# count by 1

num_charc += 1

# printing total word count


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

print("Number of words in text file: ",

num_words)

# printing total line count

print("Number of lines in text file: ",

num_lines)

# printing total character count

print('Number of characters in text file: ',

num_charc)

# printing total space count

print('Number of spaces in text file: ',

num_spaces)

# Driver Code:

if __name__ == '__main__':

fname = 'File1.txt'

try:

counter(fname)

except:

print('File not found')

Output:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

11
i) Write a program to create, display, append, insert and reverse the order of
the items in the array
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

Output:

ii) Write a program to add, transpose and multiply two matrices.

# Program to add, multiply and transpose two matrices using nested loop
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]
#Addition of two matrices
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

print("The Addition of two matrices is ")


# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)
#multiplication of two matrices
print("The multiplication of two matrices is ")
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] * Y[i][j]

for r in result:
print(r)
#Transpose of two matrices
print("The Transpose of two matrices is ")
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for j in range(len(X)):
# iterate through columns
for i in range(len(X[0])):
result[i][j] = X[j][i]

for r in result:
print(r)

output:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

iii) Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and rectangle/square.

# Import the math module to access mathematical functions like pi

import math

# Define a base class called Shape to represent a generic shape with methods for calculating area
and perimeter

class Shape:

# Placeholder method for calculating area (to be implemented in derived classes)

def calculate_area(self):

pass
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

# Placeholder method for calculating perimeter (to be implemented in derived classes)

def calculate_perimeter(self):

pass

# Define a derived class called Circle, which inherits from the Shape class

class Circle(Shape):

# Initialize the Circle object with a given radius

def __init__(self, radius):

self.radius = radius

# Calculate and return the area of the circle using the formula: π * r^2

def calculate_area(self):

return math.pi * self.radius**2

# Calculate and return the perimeter of the circle using the formula: 2π * r

def calculate_perimeter(self):

return 2 * math.pi * self.radius

# Define a derived class called Rectangle, which inherits from the Shape class

class Rectangle(Shape):

# Initialize the Rectangle object with given length and width

def __init__(self, length, width):

self.length = length

self.width = width

# Calculate and return the area of the rectangle using the formula: length * width
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

def calculate_area(self):

return self.length * self.width

# Calculate and return the perimeter of the rectangle using the formula: 2 * (length + width)

def calculate_perimeter(self):

return 2 * (self.length + self.width)

# Define a derived class called Triangle, which inherits from the Shape class

class Triangle(Shape):

# Initialize the Triangle object with a base, height, and three side lengths

def __init__(self, base, height, side1, side2, side3):

self.base = base

self.height = height

self.side1 = side1

self.side2 = side2

self.side3 = side3

# Calculate and return the area of the triangle using the formula: 0.5 * base * height

def calculate_area(self):

return 0.5 * self.base * self.height

# Calculate and return the perimeter of the triangle by adding the lengths of its three sides

def calculate_perimeter(self):

return self.side1 + self.side2 + self.side3

# Example usage

# Create a Circle object with a given radius and calculate its area and perimeter
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

r=7

circle = Circle(r)

circle_area = circle.calculate_area()

circle_perimeter = circle.calculate_perimeter()

# Print the results for the Circle

print("Radius of the circle:", r)

print("Circle Area:", circle_area)

print("Circle Perimeter:", circle_perimeter)

# Create a Rectangle object with given length and width and calculate its area and perimeter

l=5

w=7

rectangle = Rectangle(l, w)

rectangle_area = rectangle.calculate_area()

rectangle_perimeter = rectangle.calculate_perimeter()

# Print the results for the Rectangle

print("\nRectangle: Length =", l, " Width =", w)

print("Rectangle Area:", rectangle_area)

print("Rectangle Perimeter:", rectangle_perimeter)

# Create a Triangle object with a base, height, and three side lengths, and calculate its area and
perimeter

base = 5

height = 4

s1 = 4
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

s2 = 3

s3 = 5

# Print the results for the Triangle

print("\nTriangle: Base =", base, " Height =", height, " side1 =", s1, " side2 =", s2, " side3 =", s3)

triangle = Triangle(base, height, s1, s2, s3)

triangle_area = triangle.calculate_area()

triangle_perimeter = triangle.calculate_perimeter()

print("Triangle Area:", triangle_area)

print("Triangle Perimeter:", triangle_perimeter)

Output:

Radius of the circle: 7

Circle Area: 153.93804002589985

Circle Perimeter: 43.982297150257104

Rectangle: Length = 5 Width = 7

Rectangle Area: 35

Rectangle Perimeter: 24

Triangle: Base = 5 Height = 4 side1 = 4 side2 = 3 side3 = 5

Triangle Area: 10.0

Triangle Perimeter: 12
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

UNIT V:

JSON:

JSON (JavaScript Object Notation) is a text-based format for storing and exchanging data that is
easy for both humans and machines to read and write.

JSON is commonly used in web applications and API calls. For example, web developers often
use JSON to transfer data between a server and a web application

JSON represents data in two ways:

 Objects

An unordered collection of zero or more name/value pairs. Objects are defined within left ({) and
right (}) braces.

 Arrays

An ordered collection of values. Arrays are defined within left ([) and right (]) brackets.

12. Python program to check whether a JSON string contains complex object or not.

import json

def is_complex_num(objct):

if '__complex__' in objct:

return complex(objct['real'], objct['img'])


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

return objct

complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook =


is_complex_num)

simple_object =json.loads('{"real": 4, "img": 3}', object_hook = is_complex_num)

print("Complex_object: ",complex_object)

print("Without complex object: ",simple_object)

output:

13.

1. i) Python Program to demonstrate NumPy arrays creation using array () function.

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

Output:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

type(): This built-in Python function tells us the type of the object passed to it. Like in above code
it shows that arr is numpy.ndarray type.

To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and
it will be converted into an ndarray:

ii) Python program to demonstrate use of ndim, shape, size, dtype.

Get the Shape of an Array


NumPy arrays have an attribute called shape that returns a tuple with each index having the
number of corresponding elements.

The example above returns (2, 4), which means that the array has 2 dimensions, where the first
dimension has 2 elements and the second has 4.

Output:
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is
the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element
that is 3D array and 1st dim has 1 element that is a 4D array.

Output:

iii) Python program to demonstrate basic slicing, integer and Boolean indexing.
Slicing arrays

Slicing in python means taking elements from one given index to another
given index.

We pass slice instead of index like this: [start:end].


SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

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

Indexing:
Boolean Indexing:
In NumPy, boolean indexing allows us to filter elements from an array based on a specific condition.

We use boolean masks to specify the condition.

Before we learn about boolean indexing, we need to know about boolean masks.

Integer Indexing
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

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr)
#slicing
print('after slicing arr', arr[1:5])

#boolean indexing
arr1 = np.array([12, 24, 16, 21, 32, 29, 7, 15])
#arr1 > 20 creates a boolean mask that evaluates to True for elements >than 20, and
False for elements <= 20.
boolean_mask = arr1 > 20
SRK INSTITUTE OF TECHNOLOGY
Enikepadu, Vijayawada 521108
Approved by AICTE, Affiliated to JNTUK, Kakinada
(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering
Data Science (CSD) SRKIT / CSD/ 10.1
Python Programming Lab
Academic Year: 2024-2025 Class: II Semester: I

print(boolean_mask)
result = arr1[boolean_mask]
print('result after applying bool mask on arr1', result)

#integer indexing
arr2 = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr2[0, 1])

Output:

iv) Python program to find min, max, sum, cumulative sum of array

Numpy functions:

numpy.min() --- Return the minimum of an array or minimum along an axis.

numpy.minimum() -- Element-wise minimum of array elements.

numpy.max() -- Return the maximum of an array or maximum along an axis.

numpy.maximum()-- Element-wise maximum of array elements.

numpy.Sum() - Sum of array elements over a given axis.

numpy.cumulative_sum() -Return the cumulative sum of the elements along a given axis.

This function is an Array API compatible alternative to numpy.cumsum.

You might also like