Python Lab Manual
Python Lab Manual
L T P C
0 1 2 2
PYTHON PROGRAMMING
Course Objectives:
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.
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.
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.
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.
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)
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
In cmd prompt
Once installed and checked in the command prompt, open a notepad, write the program and
save as “filename”.py and save it.
Experiment 1:
# Python program to find the largest element among the three input numbers
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
Observation: Using for loops, break, lower and upper functions and keywords
Output:
X : 20
Y : 10
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
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
x = 5 # x = 0101
y = 10 # y = 1010
# Swap code
x ^= y # x = 1111, y = 1010
y ^= x # y = 0101, x = 1111
x ^= y # x = 1010, y = 0101
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
`
Experiment 2
i) Arithmetic Operators:
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
output:
a&b=0
a | b = 14
a ^ b = 14
~a = -11
a >> 1 = 5
b >> 1 = -5
a << 1 = 10
b << 1 = -20
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
print(min)
output:
a is minimum
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
output:
b is greater
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
#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.
#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
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
# Driver's code
z1 = complex(2, 3)
z2 = complex(1, 2)
print( "Addition is : ", addComplex(z1, z2))
# driver code
z1 = complex(2, 3)
z2 = complex(4, 5)
Output:
Addition is : (3+5j)
Multiplication is : (-7+22j)
num = 12
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!
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
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
delattr() Deletes the specified attribute (property or method) from the specified
object
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
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
map() Returns the specified iterator with the specified function applied to
each item
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of
where it was found
index() Searches the string for a specified value and returns the position of
where it was found
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
islower() Returns True if all characters in the string are lower case
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
partition() Returns a tuple where the string is parted into three parts
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
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
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:
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')
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
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.
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
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.
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.
def counter(fname):
num_words = 0
num_lines = 0
num_charc = 0
num_spaces = 0
# 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:
num_lines += 1
word = 'Y'
# count by 1
num_words += 1
word = 'N'
# count by 1
num_spaces += 1
word = 'Y'
for i in letter:
# incrementing character
# count by 1
num_charc += 1
num_words)
num_lines)
num_charc)
num_spaces)
# Driver Code:
if __name__ == '__main__':
fname = 'File1.txt'
try:
counter(fname)
except:
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:
# 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
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 math
# Define a base class called Shape to represent a generic shape with methods for calculating area
and perimeter
class Shape:
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
def calculate_perimeter(self):
pass
# Define a derived class called Circle, which inherits from the Shape class
class Circle(Shape):
self.radius = radius
# Calculate and return the area of the circle using the formula: π * r^2
def calculate_area(self):
# Calculate and return the perimeter of the circle using the formula: 2π * r
def calculate_perimeter(self):
# Define a derived class called Rectangle, which inherits from the Shape class
class Rectangle(Shape):
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):
# Calculate and return the perimeter of the rectangle using the formula: 2 * (length + width)
def calculate_perimeter(self):
# 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
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):
# Calculate and return the perimeter of the triangle by adding the lengths of its three sides
def calculate_perimeter(self):
# 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()
# 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()
# 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("\nTriangle: Base =", base, " Height =", height, " side1 =", s1, " side2 =", s2, " side3 =", s3)
triangle_area = triangle.calculate_area()
triangle_perimeter = triangle.calculate_perimeter()
Output:
Rectangle Area: 35
Rectangle Perimeter: 24
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
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 objct
print("Complex_object: ",complex_object)
output:
13.
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:
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.
Indexing:
Boolean Indexing:
In NumPy, boolean indexing allows us to filter elements from an array based on a specific 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.
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]])
Output:
iv) Python program to find min, max, sum, cumulative sum of array
Numpy functions:
numpy.cumulative_sum() -Return the cumulative sum of the elements along a given axis.