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

Final - Python Lab Manual

This document is a lab manual for a Python programming course at Government Polytechnic, Chintamani, detailing various lab exercises for students in the Computer Science and Engineering department. It includes instructions for Python installation, programming tasks such as calculating areas, evaluating expressions, and implementing data structures like lists and dictionaries. The manual aims to provide hands-on experience with Python programming concepts and practical applications.

Uploaded by

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

Final - Python Lab Manual

This document is a lab manual for a Python programming course at Government Polytechnic, Chintamani, detailing various lab exercises for students in the Computer Science and Engineering department. It includes instructions for Python installation, programming tasks such as calculating areas, evaluating expressions, and implementing data structures like lists and dictionaries. The manual aims to provide hands-on experience with Python programming concepts and practical applications.

Uploaded by

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

107 – GOVERNMENT POLYTECHNIC

Chintamani – 563 125

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PYTHON PROGRAMMING – 20CS31P


3rd Semester

LAB MANUAL

Name: …………………………………………………………………………….

Reg. no.: ……………………………….……………...………………………….

Sem & Year: ………………………………………...…………………………..

Branch: …………………………………………………………………………..
INDEX SHEET
Page
Sl No. Lab Programs
No.
1 Python Installation and Environmental setup. 1
Design and develop python program to compute the following.(Use
different ways of Formatting output).

a i. Area of Triangle 9
2
ii. Area of Circle
iii. Area of Rectangle

b Write a python program to evaluate expressions 10


Design and develop python program to find largest, second largest and
a 11
smallest of three numbers. (Use Nested-if statements)
Design and develop a python code to do the following.

3 i. Read Student data and marks scored in 4 subjects.

b ii. Compute total and Percentage of student. 12


iii. Declare the result and display in the form of result sheet.

(Use if-elif-else statement)


Develop python code to find the factorial of a given number. (Demo While
a 14
loop)
4
Develop a python code to print Fibonacci series for the given limit. (Demo
b 15
for loop)
a Write a python program to demonstrate set operations. 16
Write a python program to perform the following:
5
b  Basic operations on tuple 18
 Tuple indexing and slicing

Write a python program to demonstrate the following:

6 a  Basic operations on List 20


 List indexing and slicing

Write a python program to demonstrate the following:


7 a  Basic operations on Dictionary. 23
 Dictionary indexing and iterating.
a Write a python program to find the frequency of an element of the array. 26
8
b Write a python program to check the given string is palindrome or not. 27
a Write a python program to search an element of the array using Functions. 28
9 Write a python program to find the factorial of a given number using
b 29
recursion.
Write a program to implement the following.
1. Create a package which contains at least two modules.
2. Create module 1 containing arithmetic functions.
3. Create module 2 containing functions to find minimum, maximum
a 30
10 and average of given numbers.
4. Create main program which imports and executes the above
created package and modules.

b Write a program to demonstrate inbuilt modules - math and emoji. 32


Write a program to perform arithmetic operations on 2D arrays (matrices).
a 33
(Use the concept of Numpy)
11
Write a program to demonstrate statistical functions using the concept of
b 34
pandas.
Design and implement a python code to write data to a file and display file
a 36
12 object attributes.
b Write a program to read and display the content of the file. 37
a Write a program to demonstrate try and except. 38
13
b Write a program to demonstrate raising an exception. 39
20CS31P – Python Programming

WEEK 1
1. How to install python on windows.
Step 1: Select the python version to download
Visit the link [Link] to download the latest release of
python.

Step 2: Click on Install now.


Double-click the executable file, which is downloaded. Select customize the
installation and proceed. Click on the Add path to check box, it will set the python path
automatically.
Customize installation helps us to choose the desired location and features we need.

Dept. of CSE, GPT, Chintamani Page 1


20CS31P – Python Programming

Step 3: Installation in Process.


Once installation is completed, try to run python on the command prompt. Type the
command ‘python --version’.
Now, we are ready to work with python.

Pycharm Installation (IDE)

Step 1: Download Pycharm.

Visit the link [Link] to


download the executable installer.
Click on the ‘Download’ button (open source).

Dept. of CSE, GPT, Chintamani Page 2


20CS31P – Python Programming

Step 2: Click on Install now.

Double-click the executable file, which is downloaded. Select customize the


installation and proceed with ‘Next >’.
Customize installation helps us to choose the desired location and features we need.

Dept. of CSE, GPT, Chintamani Page 3


20CS31P – Python Programming

Step 3: Installation in process.

Once installation is completed, ‘Reboot computer’. After rebooting, we are ready to


work with Pycharm.

Dept. of CSE, GPT, Chintamani Page 4


20CS31P – Python Programming

To create the first program in Pycharm

Step 1: Open Pycharm editor. Click on the ‘New Project’ option to create new project.

Dept. of CSE, GPT, Chintamani Page 5


20CS31P – Python Programming

Step 2: Select a location to save the project.

 Change the project name to ‘pythonproject1’ or something meaningful.


 Pycharm will automatically find the installed Python interpreter.
 After changing the name click on the ‘Create’ button.

Step 3: Click on the ‘File’ menu and select ‘New’. From the various file formats select
‘Python file’.

Dept. of CSE, GPT, Chintamani Page 6


20CS31P – Python Programming

Step 4: Type the name of the python file and click on ‘Enter’.

Step 5: Type the first program.

i.e. print(“Hello World!”)

Step 6: Click on the ‘Run’ menu and select ‘Run’ to run your program.

Dept. of CSE, GPT, Chintamani Page 7


20CS31P – Python Programming

Step 7: You can see the output of the program at the bottom of the screen.

Dept. of CSE, GPT, Chintamani Page 8


20CS31P – Python Programming

WEEK 2 (Lab Programs)


2a) Design and develop python program to compute the following.(Use different ways of
Formatting output).
i. Area of Triangle
ii. Area of Circle
iii. Area of Rectangle

iv. base = eval(input('Enter the base of triangle: '))


height = eval(input('Enter the height of triangle: '))
radius = eval(input('Enter the radius of circle: '))
length = eval(input('Enter the length of rectangle: '))
breadth = eval(input('Enter the breadth of rectangle: '))

str1 = 'Area of Triangle'


str2 = 'Area of Circle'
str3 = 'Area of Rectangle'

print([Link](40, '-'))
area_triangle = 0.5 * base * height
print('Base: ', base)
print('Height: ', height)
print('Area: ', area_triangle)

print([Link](40, '-'))
area_circle = 3.14 * radius * radius
print('Radius: ', radius)
print('Area: ', area_circle)

print([Link](40, '-'))
area_rectangle = length * breadth
print('Length: ', length)
print('Breadth: ', breadth)
print('Area: ', area_rectangle)

Output:
Enter the base of triangle: 6
Enter the height of triangle: 4
Enter the radius of circle: 5
Enter the length of rectangle: 8
Enter the breadth of rectangle: 3
------------Area of Triangle------------
Base: 6
Height: 4
Area: 12.0

Dept. of CSE, GPT, Chintamani Page 9


20CS31P – Python Programming

-------------Area of Circle-------------
Radius: 5
Area: 78.5
-----------Area of Rectangle------------
Length: 8
Breadth: 3
Area: 24

2b) Write a python program to evaluate expressions


num1 = eval(input('Enter first number: '))
num2 = eval(input('Enter Second number: '))

sum1 = num1 + num2


diff = num1 - num2
mul = num1 * num2
div = num1 / num2
remainder = num1 % num2
avg = (num1 + num2) / 2

print("The 2 numbers are {} and {}".format(num1, num2))

print("Output of evaluated Expressions........")


print('The sum: ', sum1)
print('The difference: ', diff)
print('The product:', mul)
print('The Quotient:', div)
print('The remainder: ', remainder)
print('The average: ', avg)

Output:
Enter first number: 46
Enter second number: 24
The 2 numbers are 46 and 24
Ouput of evaluated Expressions........
The sum: 70
The difference: 22
The product: 1104
The Quotient: 1.9166666666666667
The remainder: 22
The average: 35.0

Dept. of CSE, GPT, Chintamani Page 10


20CS31P – Python Programming

WEEK 3 (Lab Programs)


3.a) Design and develop python program to find largest, second largest and smallest of
three numbers. (Use Nested-if statements)
a = eval(input('Enter the first number: '))
b = eval(input('Enter the second number: '))
c = eval(input('Enter the third number: '))

large = a
if b > large:
if b > c:
large = b
else:
large = c

small = a
if b < small:
small = b
if c < small:
small = c

sec_large = (a + b + c) - (large + small)

print('The largest is', large)


print('The second largest is', sec_large)
print('The smallest is', small)

Output:
Enter the first number: 6
Enter the second number: 9
Enter the third number: 3
The largest is 9
The second largest is 6
The smallest is 3

Dept. of CSE, GPT, Chintamani Page 11


20CS31P – Python Programming

3.b) Design and develop a python code to do the following.


i. Read Student data and marks scored in 4 subjects.
ii. Compute total and Percentage of student.
iii. Declare the result and display in the form of result sheet.
(Use if-elif-else statement)
name = input("Enter your Name:")
regno = input("Enter your register number :")

m1, m2, m3, m4 = [int(i) for i in input('Enter subject 1,


2, 3 and 4 marks using spaces : ').split(' ')]

str1 = "STUDENT DETAILS"


str2 = "RESULT SHEET"

print([Link](50, '*'))
print('Name:',name)
print('Register Number:',regno)

print([Link](50, '*'))
print('The marks of Python is', m1)
print('The marks of Hardware is', m2)
print('The marks of Computer Network is', m3)
print('The marks of DBMS is', m4)

per = (m1 + m2 + m3 + m4) / 400 * 100


print("Total :", total)
print("Percentage :", per)

if per >= 75 and per <= 100:


print('Result : Distinction')
elif per >= 60 and per < 75:
print('Result : First Class')
elif per >= 50 and per < 60:
print('Result : Second Class')
elif per >= 40 and per < 50:
print('Result : Pass')
else:
print('Result : Fail')

Output:
Enter your Name:Ram
Enter your register number :CS0012
Enter subject 1, 2, 3 and 4 marks using spaces : 87 76 78 97

Dept. of CSE, GPT, Chintamani Page 12


20CS31P – Python Programming

*****************STUDENT DETAILS******************
Name: Ram
Register Number: CS0012
*******************RESULT SHEET*******************
The marks of Python is 87
The marks of Hardware is 76
The marks of Computer Network is 78
The marks of DBMS is 97
Percentage : 84.5
Result : Distinction

Dept. of CSE, GPT, Chintamani Page 13


20CS31P – Python Programming

WEEK 4 (Lab Programs)


4.a) Develop python code to find the factorial of a given number. (Demo While loop)
num = int(input('Enter the number: '))
print('The given number is', num)

fact = 1

if num < 0:

print("Factorial doesn't exist for Negative numbers …!!")

elif num == 0:

print('The Factorial of 0 (Zero) is 1')

else:

while num > 0:

fact = fact * num


num = num – 1

print('Factorial of a given number is:', fact)

Output:
Case1:
Enter the number: 5
The given number is 5
Factorial of a given number is: 120
Case2:
Enter the number: 0
The given number is 0
The Factorial of 0 (Zero) is 1
Case3:
Enter the number: -2
The given number is -2
Factorial doesn't exist for Negative numbers !!..

Dept. of CSE, GPT, Chintamani Page 14


20CS31P – Python Programming

4.b) Develop a python code to print Fibonacci series for the given limit. (Demo for loop)
nterms = int(input('Enter the terms for Fibonacci series:'))

str1 = 'Fibonacci series'


print([Link](50, '-'))

num1 = 0
num2 = 1

for i in range(nterms):

print(num1, end = ' ')

num = num1 + num2

num1 = num2
num2 = num

Output 1:
Enter the terms for Fibonacci series: 12
-----------------Fibonacci series-----------------
0 1 1 2 3 5 8 13 21 34 55 89

Output 2:
Enter the terms for Fibonacci series: 9
-----------------Fibonacci series-----------------
0 1 1 2 3 5 8 13 21

Dept. of CSE, GPT, Chintamani Page 15


20CS31P – Python Programming

WEEK 5 (Lab Programs)


5.a) Write a python program to demonstrate set operations.
# creating empty set
set1 = set()
# creating set with elements
set2 = {5, 7, 2}
print('Created sets....')
print('set1:', set1)
print('set2:', set2)

# adding elements to set1 and set2


for i in range(1, 7):
[Link](i)
[Link]([2, 4, 6, 1, 8, 9])
print('After adding elements to sets...')
print('set1:', set1)
print('set2:', set2)

# removing set elements


[Link](5)
[Link](8)
print('After removing elements 6 and 8')
print('Original sets.......')
print('set1: ', set1)
print('set2: ', set2)

# set union
union = [Link](set2)
print("Union of set1 and set2 is ", union)

# set intersection
common = [Link](set2)
print("Intersection of set1 and set2 is ", common)

# set difference
diff = [Link](set2)
print("Difference of set1 and set2 is ", diff)

Dept. of CSE, GPT, Chintamani Page 16


20CS31P – Python Programming

Output:
Created sets....
set1: set()
set2: {2, 5, 7}
After adding elements to sets...
set1: {1, 2, 3, 4, 5, 6}
set2: {1, 2, 4, 5, 6, 7, 8, 9}
After removing elements 6 and 8
Original sets.......
set1: {1, 2, 3, 4, 6}
set2: {1, 2, 4, 5, 6, 7, 9}
Union of set1 and set2 is {1, 2, 3, 4, 5, 6, 7, 9}
Intersection of set1 and set2 is {1, 2, 4, 6}
Difference of set1 and set2 is {3}

Dept. of CSE, GPT, Chintamani Page 17


20CS31P – Python Programming

5.b) Write a python program to perform the following:


 Basic operations on tuple
 Tuple indexing and slicing

#creating empty tuple


tup = ()
print('Empty tuple: ', tup)

#creating typle with elements


single_tup = (1,)
print('Single tuple: ', single_tup)

tup1 = 1, 2, 3, 4, 1, 2, 1
tup2 = (1, 2, 3, 4, (5, 6, 7))
print('Tuple elements inside parentheses or without
parentheses '
'prints tuple only')
print('Tuple1: ', tup1)
print('Tuple2: ', tup2)

#tuple methods
count = [Link](2)
print('In tuple1 element 2 count is', count)
index = [Link](3)
print('In tuple2 the element location of 3 is in index',
index)

#tuple indexing
print('Accessing tuple2 elements....')
a = tup2[3]
print('The element in 3rd index is', a)
b = tup2[-4]
print('The element in -4th index is', b)
c = tup2[-1][2]
print('The last element inside nested tuple is', c)

#tuple slicing
print('Accessing tuple2 range of elements....')
d = tup2[:4]
print('The elements from index range 0 to 4 is', d)
e = tup2[2:4]
print('The elements from index range 2 to 4 is', e)

Dept. of CSE, GPT, Chintamani Page 18


20CS31P – Python Programming

f = tup2[0:]
print('To print every element: ', f)
g = tup2[-4:-1]
print('The elements from index range -4 to -1 is', g)

Output:
Empty tuple: ()

Single tuple: (1,)


Tuple elements inside parentheses or without parentheses prints tuple only
Tuple1: (1, 2, 3, 4, 1, 2, 1)

Tuple2: (1, 2, 3, 4, (5, 6, 7))


In tuple1 element 2 count is 2
In tuple2 the element location of 3 is in index 2

Accessing tuple2 elements....


The element in 3rd index is 4
The element in -4th index is 2

The last element inside nested tuple is 7


Accessing tuple2 range of elements....
The elements from index range 0 to 4 is (1, 2, 3, 4)

The elements from index range 2 to 4 is (3, 4)


To print every element: (1, 2, 3, 4, (5, 6, 7))
The elements from index range -4 to -1 is (2, 3, 4)

Dept. of CSE, GPT, Chintamani Page 19


20CS31P – Python Programming

WEEK 6 (Lab Programs)


6a) Write a python program to demonstrate the following:
 Basic operations on List
 List indexing and slicing

# creating empty tuple


list0 = []
print('Empty list: ', list0)

# creating list with elements


list1 = [2, 4, 6]
list2 = [1, 3, 5, 7, 9, (2, 4, 6)]
print('Original lists.......')
print('list1: ', list1)
print('list2: ', list2)
print()

# Adding elements of list1


for i in range(4):
n = int(input('Enter the element to add: '))
[Link](n)
print('After adding elements to list1')
print(list1)

# changing elements of list1


list1[1] = 5
list1[0] = 1
print('Updated list1: ', list1)
print()

# removing elements of list1 using index


[Link](-1)
del list1[3]
# removing elements of list using value
[Link](6)
print('After removing some elements in list1')
print(list1)

# list indexing
print('Accessing list2 elements....')
a = list2[3]
print('The element in 3rd index is', a)
b = list2[-4]

Dept. of CSE, GPT, Chintamani Page 20


20CS31P – Python Programming

print('The element in -4th index is', b)


c = list2[-1][2]
print('The last element inside nested list is', c)
print()

# list slicing
print('Accessing list2 range of elements....')
d = list2[:4]
print('The elements from index range 0 to 4 is', d)
e = list2[2:4]
print('The elements from index range 2 to 4 is', e)
f = list2[0:]
print('To print every element: ', f)
g = list2[-4:-1]
print('The elements from index range -4 to -1 is', g)

Output:

Empty list: [ ]

Original lists.......

list1: [2, 4, 6]

list2: [1, 3, 5, 7, 9, (2, 4, 6)]

Enter the element to add: 7

Enter the element to add: 4

Enter the element to add: 9

Enter the element to add: 3

After adding elements to list1

[2, 4, 6, 7, 4, 9, 3]

Updated list1: [1, 5, 6, 7, 4, 9, 3]

Dept. of CSE, GPT, Chintamani Page 21


20CS31P – Python Programming

After removing some elements in list1


[1, 5, 4, 9]

Accessing list2 elements....


The element in 3rd index is 7
The element in -4th index is 5

The last element inside nested list is 6

Accessing list2 range of elements....

The elements from index range 0 to 4 is [1, 3, 5, 7]


The elements from index range 2 to 4 is [5, 7]
To print every element: [1, 3, 5, 7, 9, (2, 4, 6)]

The elements from index range -4 to -1 is [5, 7, 9]

Dept. of CSE, GPT, Chintamani Page 22


20CS31P – Python Programming

Week 7 (Lab Programs)


7. Write a python program to demonstrate the following:
 Basic operations on Dictionary.
 Dictionary indexing and iterating.

# Creating empty dictionary


Dict = {}
print('Type of Dict:', type(Dict))
print('Empty dictionary:', Dict)
# Creating dictionary with dict() method
dict1 = dict({1: 'Python', 2: 'Pycharm'})
# Creating dictionary with each item as a pair
dict2 = dict([('Name', 'John'), ('Age', 22)])
print('Created dictionaries.....')
print('dict1: ', dict1)
print('dict2: ', dict2)
print()

# Adding dictionary items


dict1[3] = 'Pydev'
dict1[4] = 'Spyder', 'Jupyter'
dict2['Salary'] = 25000
print('After adding items to dict1 and dict2.....')
print('dict1: ', dict1)
print('dict2: ', dict2)
print()

# Updating dictionary items


dict2['Salary'] = 30000
print('Updated Dictionary:', dict2)

# Removing items of dictionary


del dict2['Salary']
del dict2['Age']

Dept. of CSE, GPT, Chintamani Page 23


20CS31P – Python Programming

print('After removing items from dict2....')


print(dict2)

# Dictionary indexing
print('Accessing dict1 values....')
print('The value of key 1: ', dict1[1])
print('The value of key 4: ', dict1[4])
print()

# Iterating dictionary items


print('Iterating dictionary keys only....')
for i in dict1:
print(i)

print('Iterating dictionary values only....')


for i in [Link]():
print(i)

print('Iterating dictionary Keys with values....')


for i in [Link]():
print(i)

Output:
Type of Dict: <class 'dict'>
Empty dictionary: {}
Created dictionaries.....
dict1: {1: 'Python', 2: 'Pycharm'}
dict2: {'Name': 'John', 'Age': 22}

After adding items to dict1 and dict2.....


dict1: {1: 'Python', 2: 'Pycharm', 3: 'Pydev', 4: ('Spyder', 'Jupyter')}
dict2: {'Name': 'John', 'Age': 22, 'Salary': 25000}

Dept. of CSE, GPT, Chintamani Page 24


20CS31P – Python Programming

Updated Dictionary: {'Name': 'John', 'Age': 22, 'Salary': 30000}


After removing items from dict2....
{'Name': 'John'}
Accessing dict1 values....
The value of key 1: Python
The value of key 4: ('Spyder', 'Jupyter')

Iterating dictionary keys only....


1
2
3
4
Iterating dictionary values only....
Python
Pycharm
Pydev
('Spyder', 'Jupyter')
Iterating dictionary Keys with values....
(1, 'Python')
(2, 'Pycharm')
(3, 'Pydev')
(4, ('Spyder', 'Jupyter'))

Dept. of CSE, GPT, Chintamani Page 25


20CS31P – Python Programming

WEEK 8 (Lab Programs)

8.a) Write a python program to find the frequency of an element of the array.
import array as arr

a = [Link]('i')
size = int(input('Enter the size of an array: '))

print('Enter %d elements'% size)


for i in range(size):
n = int(input())
[Link](n)

ele = int(input('Enter the element to find frequency:'))


print()
str1 = 'Printing the Array'
print([Link](50, '-'))
print(a)
print()

count = 0

for i in range(size):
if ele == a[i]:
count = count + 1

print('The element {} occurs {} times in given


array'.format(ele, count)

Output:

Enter the size of an array: 6


Enter 6 elements
3
6
7
8
8
8
Enter the element to find frequency: 8

Dept. of CSE, GPT, Chintamani Page 26


20CS31P – Python Programming

----------------Printing the Array----------------


array('i', [3, 6, 7, 8, 8, 8])

The element 8 occurs 3 times in given array

8.b) Write a python program to check the given string is palindrome or not.
str1 = input('Enter one string: ')

print("The given string is:", str1)

rev_str = str1[::-1]

if str1 == rev_str:

print("The string is palindrome")

else:

print("The string is not palindrome")

Output1:

Enter one string: madam


The given string is: madam
The string is palindrome

Output2:

Enter one string: 10101


The given string is: 10101
The string is palindrome

Output3:

Enter one string: hello


The given string is: hello
The string is not palindrome

Dept. of CSE, GPT, Chintamani Page 27


20CS31P – Python Programming

WEEK 9 (Lab Programs)

9.a) Write a python program to search an element of the array using Functions.

import array as arr

loc = -1

def search1(a1, ele):


global loc
for i in range(size):
if ele == a1[i]:
loc = i
break
return loc

a = [Link]('i')
size = int(input('Enter the size of an array: '))

print('Enter %d elements' % size)


for i in range(size):
n = int(input())
[Link](n)

key = int(input('Enter the key element to search: '))


print()

b = search1(a, key)

if b == -1:
print('The element does not in the array')
else:
print('Search Successful')
print('The element %d found at index %d ' % (key,b))

Output:

Enter the size of an array: 5


Enter 5 elements
7
6
4
8
9
Enter the key element to search: 4

Search Successful
The element 4 found at index 2

Dept. of CSE, GPT, Chintamani Page 28


20CS31P – Python Programming

9.b) Write a python program to find the factorial of a given number using recursion.

def fact(num):
if num == 0:
return 1
factorial = num * fact(num - 1)
return factorial

n = int(input('Enter the number to find factorial: '))


print('The given number is', n)

if n < 0:
print("Factorial doesn't exist for negative numbers")
else:
print('The factorial is', fact(n))

Output1:
Enter the number to find factorial: -5
The given number is -5
Factorial doesn't exist for negative numbers

Output2:
Enter the number to find factorial: 0
The given number is 0
The factorial is 1

Output3:
Enter the number to find factorial: 7
The given number is 7
The factorial is 5040

Dept. of CSE, GPT, Chintamani Page 29


20CS31P – Python Programming

WEEK 10 (Lab Programs)

10. a) Write a program to implement the following.


1. Create a package which contains at least two modules.
2. Create module 1 containing arithmetic functions.
3. Create module 2 containing functions to find minimum, maximum and
average of given numbers.
4. Create main program which imports and executes the above created package
and modules.

Operations (python package)


 arith (module)
 Numc (module)

[Link]
def add(a, b):
return a + b

def sub(a, b):


return a - b

def mul(a, b):


return a * b

def div(a, b):


return a / b

def mod(a, b):


return a % b

[Link]

def mini(a, b):


return min(a, b)

def maxi(a, b):


return max(a, b)

def avg(a, b):


c = a + b
return c / 2

Dept. of CSE, GPT, Chintamani Page 30


20CS31P – Python Programming

[Link]

import [Link] as a
import [Link] as n

x = eval(input('Enter First number: '))


y = eval(input('Enter Second number: '))
print('The given numbers are %d and %d' % (x, y))

print()
str1 = 'arith module Operations'
print([Link](50, '-'))
print('sum is', [Link](x, y))
print('Difference is', [Link](x, y))
print('Product is', [Link](x, y))
print('Division is', [Link](x, y))
print('Remainder is', [Link](x, y))

print()
str2 = 'Numc module Operations'
print([Link](50, '-'))
print('Minimum is', [Link](x, y))
print('Maximum is', [Link](x, y))
print('Average is', [Link](x, y))

Output:

Enter First number: 4


Enter Second number: 2
The given numbers are 4 and 2

-------------arith module Operations--------------


sum is 6
Difference is 2
Product is 8
Division is 2.0
Remainder is 0

--------------Numc module Operations--------------


Minimum is 2
Maximum is 4
Average is 3.0

Dept. of CSE, GPT, Chintamani Page 31


20CS31P – Python Programming

10. b) Write a program to demonstrate inbuilt modules - math and emoji.

import math
import emoji

x = eval(input('Enter first number: '))


y = eval(input('Enter Second number: '))
print('The given numbers are %d and %d' % (x, y))

print()
str1 = 'Math module operations'
print([Link](50, '-'))
print('The square root of first number is', [Link](x))
print('The square root of second number is', [Link](y))
z = [Link](x, y)
print('value of %d ^ %d is %d ' % (x, y, z))

print()
str2 = 'Emoji module operations'
print([Link](50, '-'))
a = [Link](':grinning_face:')
b = [Link](':beaming_face_with_smiling_eyes:')
print('Grinning face: ', a)
print('Beaming face: ', b)

c = [Link]('😉')
d = [Link]('�')
print('CLDR short name of 😉 is', c)
print('CLDR short name of � is', d)

Output:

Enter first number: 2


Enter Second number: 4
The given numbers are 2 and 4

--------------Math module operations--------------


The square root of first number is 1.4142135623730951
The square root of second number is 2.0
value of 2 ^ 4 is 16

-------------Emoji module operations--------------


Grinning face: 😀
Beaming face: 😁
CLDR short name of 😉 is :winking_face:
CLDR short name of � is :rolling_on_the_floor_laughing:

Dept. of CSE, GPT, Chintamani Page 32


20CS31P – Python Programming

WEEK 11 (Lab Programs)


11. a) Write a program to perform arithmetic operations on 2D arrays (matrices).
(Use the concept of Numpy)

import numpy as np
m1 = [Link]([[2,3],[4,2]])
print('Matrix 1: \n', m1)
m2 = [Link]([[1, 2], [2, 4]])
print('Matrix 2: \n', m2)

sum1 = [Link](m1, m2)


diff = [Link](m1, m2)
mul = [Link](m1, m2)
mul2 = [Link](m1, m2)
div = [Link](m1, m2)

print()
str1 = 'Arithmetic operations on 2D arrays'
print([Link](50, '-'))
print('Sum of two matrices is \n', sum1)
print('Difference of two matrices is \n', diff)
print('Product of two matrices is \n', mul)
print('Product of two matrices using dot function is
\n', mul2)
print('Division of two matrices is \n', div)

Output:

Matrix 1:
[[2 3]
[4 2]]
Matrix 2:
[[1 2]
[2 4]]

--------Arithmetic operations on 2D arrays--------


Sum of two matrices is
[[3 5]
[6 6]]
Difference of two matrices is
[[ 1 1]
[ 2 -2]]
Product of two matrices is
[[2 6]
[8 8]]

Dept. of CSE, GPT, Chintamani Page 33


20CS31P – Python Programming

Product of two matrices using dot function is


[[ 8 16]
[ 8 16]]
Division of two matrices is
[[2. 1.5]
[2. 0.5]]

11. b) Write a program to demonstrate statistical functions using the concept of


pandas.
import pandas as pd
data = {
'Name': ['Parker', 'Smith', 'John', 'William'],
'Math_marks': [52, 38, 42, 37],
'Sci_marks': [41, 35, 29, 36]
}
df = [Link](data)
str1 = 'Data table'
print([Link](50, '-'))
print(df)

print()
str2 = 'Mean of subjects'
print([Link](50, '-'))
print([Link](numeric_only=True))

print()
str3 = 'Standard Deviation of subjects'
print([Link](50, '-'))
print([Link](numeric_only=True))

print()
str4 = 'Variance of subjects'
print([Link](50, '-'))
print([Link](numeric_only=True))

Dept. of CSE, GPT, Chintamani Page 34


20CS31P – Python Programming

Output:

--------------------Data table--------------------
Name Math_marks Sci_marks
0 Parker 52 41
1 Smith 38 35
2 John 42 29
3 William 37 36

-----------------Mean of subjects-----------------
Math_marks 42.25
Sci_marks 35.25
dtype: float64

----------Standard Deviation of subjects----------


Math_marks 6.849574
Sci_marks 4.924429
dtype: float64

---------------Variance of subjects---------------
Math_marks 46.916667
Sci_marks 24.250000
dtype: float64

Dept. of CSE, GPT, Chintamani Page 35


20CS31P – Python Programming

WEEK 12 (Lab Programs)

12. a) Design and implement a python code to write data to a file and display file object
attributes.
f = open('[Link]', 'w')

# writing with single line string


[Link]('Python is a modern language.\nIt is simple to
learn.')

# writing with multi line string


[Link]('''It is object-oriented and easy to use.
An open source language with standard libraries.''')

print("File Written Successfully")

[Link]()

# file object attributes


print('The file name is', [Link])
print('The mode of file is', [Link])
print('Is file closed? ', [Link])

Console output:

File Written Successfully


The file name is [Link]
The mode of file is w
Is file closed? True

File Content:

Dept. of CSE, GPT, Chintamani Page 36


20CS31P – Python Programming

12. b) Write a program to read and display the content of the file.

f = open('[Link]', 'r')

# to read single line


a = [Link]()
print('Reading single line'.center(40,'-'))
print(a)

# to read everything in file


b = [Link]()
print('Reading remaining content in file'.center(40,'-'))
print(b)
print()

[Link]()

print('Iterating on files'.center(40,'-'))
f1 = open('[Link]','r')
print()
for i in f1:
print(i)
[Link]()

Output:

----------Reading single line-----------


Python is a modern language.

---Reading remaining content in file----


It is simple to [Link] is object-oriented and easy to use.
An open source language with standard libraries.

-----------Iterating on files-----------

Python is a modern language.

It is simple to [Link] is object-oriented and easy to use.

An open source language with standard libraries.

Dept. of CSE, GPT, Chintamani Page 37


20CS31P – Python Programming

WEEK 13 (Lab Programs)

13. a) Write a program to demonstrate try and except.


def f1(dv1, dvr):
q = dv1 / dvr
return q

def f2(num):
print('The integer number is', num)

try:
a = int(input('Enter the dividend: '))
b = int(input('Enter the divisor: '))
c = f1(a, b)
if c:
print('The quotient is ', c)
except:
print('ArithmeticError')
print('Sorry, no number can be divided by Zero')

print()
try:
d = int(input('Enter the integer number: '))
f2(d)
except:
print('ValueError')
print('Only integer numbers allowed')

Output:

Enter the dividend: 5


Enter the divisor: 0
ArithmeticError
Sorry, no number can be divided by Zero

Enter the integer number: 2.4


ValueError
Only integer numbers allowed

Dept. of CSE, GPT, Chintamani Page 38


20CS31P – Python Programming

13. b) Write a program to demonstrate raising an exception.

tup = (5, 6, 3, 8, 7)
print('Given tuple: ',tup)

print()
print('try updating tuple values..............')
a = int(input('Enter the value to be updated: '))
b = int(input('Enter the index to be updated: '))

print( n )
if b > 4:
raise IndexError('You have crossed Index limit')
else:
try:
# trying to update tup value
tup[b] = a
except:
print('TypeError')
print("You are not allowed to update tuple")
finally:
print('End of program')

Output1:

Given tuple: (5, 6, 3, 8, 7)

try updating tuple values..............


Enter the value to be updated: 5
Enter the index to be updated: 6

Traceback (most recent call last):


File "C:\Users\new\PycharmProjects\week10\[Link]", line 12, in <module>
raise IndexError('You have crossed Index limit')
IndexError: You have crossed Index limit

Output2:
Given tuple: (5, 6, 3, 8, 7)

try updating tuple values..............


Enter the value to be updated: 5
Enter the index to be updated: 4

TypeError
You are not allowed to update tuple
End of program

Dept. of CSE, GPT, Chintamani Page 39

You might also like