Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views26 pages

Python Lab Manual 2025

Uploaded by

kavyagouda257
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)
6 views26 pages

Python Lab Manual 2025

Uploaded by

kavyagouda257
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
You are on page 1/ 26

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY

AND MANAGEMENT
Udayapura, Kanakapura Road, Opp. Art of Living, Bangalore – 560082
(Affliated to VTU, Belagavi, Approved by AICTE, New Delhi, Accredited by NBA, New Delhi)
(Autonomous to VTU)

2024-2025
Introduction to Python Programming
Laboratory Manual
(23PLCS21)
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &
MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New
Delhi, Accredited by NBA for 3 years, New Delhi)

VISION OF THE INSTITUTE


To strive at creating the institution a center of highest caliber of learning, so as to create an
overall intellectual atmosphere with each deriving strength from the other to be the best of
engineers, scientists and mathematicians.

MISSION OF THE INSTITUTE


• To serve its region, state, the nation and globally by preparing students to make meaningful
contributions in an increasing complex global society.
• To encourage, reflection on and evaluation of emerging needs and priorities with state of art
infrastructure.
• To support research and services establishing enhancements in technical, health, economic,
human and cultural development.
• To establish inter disciplinary center of excellence.
• To increase the number of Doctorate holders to promote research culture on campus.
QUALITY POLICY
"We, at "Dayananda Sagar Academy of Technology and Management" are committed to
continually improve and deliver competitive quality technical education to the at most
satisfaction of student, their parents and potential employer."

OBJECTIVES & GOALS

1. Creating an academic environment to develop the younger generation and providing quality
professional engineering education at an affordable cost.
2. Create necessary infrastructure on a continuous basis the professional education with the
changing needs of society.
3. Optimum utilization of the infrastructure and resources to achieve excellence in the
engineering courses.
4. Monitor continuously the growth in technology parts of the world and address all aspects of
development of human resource (both from academic and supporting staff) and students to be in
tune with state of the art technology and engineering practices.
5. Facilitate greater Industry, Institute, and Interaction so as to empower the students with
practical knowledge.
6. Institute various quality assurance systems.
7. Adopting learning beyond curriculum process.
8. Initiate systems of learning which are based on enable students to acquire skills relevant to their
career.
9. To continuous monitor, asses evaluate the various academic programs adopting outcome-based
education.
INTRODUCTION TO PYTHON PROGRAMMING
LABORATORY
Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)
(Effective from the academic year 2023 – 24)

Course Code 23PLCS21 CIE Marks 50


Teaching Hours/Week (L: T:P: S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy -- Total Marks 100
Credits 03 Exam Hours 03

List of problems for which students should develop the program and execute in the
Laboratory
Sl. No. Experiments/Programs Page No.
a. Develop a program to read the student details like Name, USN, and Marks in three
subjects. Display the student details, total marks and percentage with suitable messages.
1 1
b. Develop a Python program to check whether a given number is palindrome or not and
also count the number of occurrences of each digit in the input number

a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
2 console. 4
b. Write a function to calculate factorial of a number with and without recursion.
a. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages using functions.
3 10
b. Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.

Read a multi-digit number (as chars) from the console. Develop a program to print the
4 14
frequency of each digit with suitable messages.
a. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary with distinct words and their frequency of occurrences. Sort the dictionary in
the reverse order of frequency and display dictionary slice of first 10 items]
5 16
b. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(),
and file methods open(), read lines(), and write()].

a. Develop a program to backing Up a given Folder (Folder in a current working directory)


into a ZIP File by using relevant modules and suitable methods.

6 b. Write a function named DivExp which takes TWO parameters a, b and returns a value c 17
(c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception for
when b=0. Develop a suitable program which reads two values from the console and
calls a function DivExp.

a. Develop a Python program to demonstrate find all function and character class using
7 regex module. 19
b. Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected]).
Define a function which takes TWO objects representing complex numbers and returns new
complex number with a addition of two complex numbers. Define a suitable class
8 24
‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.

Develop a program that uses class Student which prompts the user to enter marks in three
subjects and calculates total marks, percentage and displays the score card details. [Hint:
9 Use list to store the marks in three subjects and total marks. Use init () method to 29
initialize name, USN and the lists to store marks and total, Use getMarks() method to read
marks into the list, and display() method to display the score card details.].

10 Develop a program to convert list and dictionary into NumPy array 32


Open ended Programs
1 Design a web page using Flask in python.
2 Demonstrate Web scraping using suitable example.
3 Demonstrate API Integration.
4 Demonstrate about Data Visualization.
5 Demonstrate GUI Applications
6 Demonstrate E-mail Automation.

CIE for Introduction to Python Programming (Integrated Professional Core Course (IPCC)):
This Course refers to Professional Theory Core Course Integrated with Practical Component Credit for this
course can be 03 and its Teaching Learning hours (L: T: P: PJ) can be considered as (2: 0: 2: 0).

CIE for Practical component of the PLC/PBL:


15 marks for the conduction of practical experiment and preparation of the Laboratory record, and 10 marks
for the test to be conducted after the completion of all the laboratory sessions.
On completion of every program in the laboratory, the student shall be evaluated including viva-voce and
marks shall be awarded on the same day.
Each program report can be evaluated for 15 marks (Write-up – 3 marks, Execution – 8 marks .and Viva – 4
marks)
The Laboratory test (duration 2 hours / 3 hours) after completion of all the programs shall be conducted for 50
marks and scaled down to 10 marks.
The project review (periodical review) shall be conducted for 50 marks and scale down to 10 marks.
The theory part shall be evaluated both by CIE and SEE. The practical part shall be evaluated by only CIE (no
SEE). However, questions from the practical part of PLC/PBL shall be included in the SEE question paper.
This course is common to all branches of first year B.E 2023-24 regulation.

Note: L- Theory Lecture, T- Tutorial, P-Practical, PJ-Project, CIE: Continuous Internal Evaluation, SEE:
Semester End Examination.
PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-1
a. Develop a program to read the student details like Name, USN, and Marks in three
subjects. Display the student details, total marks and percentage with suitable
messages.

stName = input("Enter the name of the student : ")


stUSN = input("Enter the USN of the student : ")
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))
print("Student Details\n=========================")
print("%12s"%("Name :"), stName)
print("%12s"%("USN :"), stUSN)
print("%12s"%("Marks 1 :"), stMarks1)
print("%12s"%("Marks 2 :"), stMarks2)
print("%12s"%("Marks 3 :"), stMarks3)
print("%12s"%("Total :"), stMarks1+stMarks2+stMarks3)
print("%12s"%("Percent :"), "%.2f"%((stMarks1+stMarks2+stMarks3)/3))
print("=========================")
Output:
Enter the name of the student :Agasthya
Enter the USN of the student :1XY20IS001
Enter marks in Subject 1 :79
Enter marks in Subject 2 :85
Enter marks in Subject 3 :93
Student Details
=========================
Name :Agasthya
USN :1XY20IS001
Marks 1 :79
Marks 2 :85
Marks 3 :93
Total :257
Percent :85.67
=========================

DSATM, Bangalore-82 Page 1


PYTHON PROGRAMMING LABORATORY 23PLCS21

b. Develop a Python program to check whether a given number is palindrome or not


and also count the number of occurrences of each digit in the input number

Ans 1:
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
rem=n%10
rev=rev*10+rem
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
n=temp
for i in range(10):
temp=n
count=0
while temp>0:
if(temp % 10 == i):
count = count + 1
temp = temp // 10
print( i, "occurs", count, "times in the input")
Output
Run 1 Run 2:
Enter number:122267484 Enter number:1335331
The number isn't a palindrome! The number is a palindrome!
0 occurs 0 times in the input 0 occurs 0 times in the input
1 occurs 1 times in the input 1 occurs 2 times in the input
2 occurs 3 times in the input 2 occurs 0 times in the input
3 occurs 0 times in the input 3 occurs 4 times in the input
4 occurs 2 times in the input 4 occurs 0 times in the input
5 occurs 0 times in the input 5 occurs 1 times in the input
6 occurs 1 times in the input 6 occurs 0 times in the input
7 occurs 1 times in the input 7 occurs 0 times in the input
8 occurs 1 times in the input 8 occurs 0 times in the input
9 occurs 0 times in the input 9 occurs 0 times in the input

DSATM, Bangalore-82 Page 2


PYTHON PROGRAMMING LABORATORY 23PLCS21

Ans 2:
val = int(input("Enter a value : "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i), "appears", str_val.count(str(i)), "times");
Output
Run 1 Run 2
Enter a value : 13531 Enter a value : 123134
Palindrome Not Palindrome
1 appears 2 times 1 appears 2 times
3 appears 2 times 2 appears 1 times
5 appears 1 times 3 appears 2 times
4 appears 1 times

DSATM, Bangalore-82 Page 1


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-2

a) Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.

def fibonacci(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
return fibonacci(num-2)+fibonacci(num-1)
n = int(input("Enter the value of N : "))
for i in range(0, n):
print(fibonacci (i), end=" ")
Output
Enter the value of N : 5
01123
b) Write a function to calculate the factorial of a number with and without recursion.
With Recursion:

def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
n = int(input("Enter the value of N : "))
factorial = fact(n)
print(n,'!'," = ",factorial,sep="")

Output
Enter the value of N : 5
5! = 120

DSATM, Bangalore-82 Page 2


PYTHON PROGRAMMING LABORATORY 23PLCS21

Without recursion:

def fact(num):
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
return
elif num == 0:
return 1
else:
factorial=1
for i in range(1,num + 1):
factorial = factorial*i
return factorial
num = int(input("Enter a number: "))
factorial = fact(num)
print("The factorial of",num,"is",factorial)

Output
Enter a number: 6
The factorial of 6 is 720

DSATM, Bangalore-82 Page 3


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-3
a) Read N numbers from the console and create a list. Develop a program to print
mean, variance and standard deviation with suitable messages using functions.
Ans 1(using built-in functions):
import statistics
Numlist = []
n = int(input("Enter the value of n : "))
for i in range(0, n):
ele = int(input('Enter number '+ str(i+1)))
Numlist.append(ele)
print('The list of elements is',Numlist)
print('Mean=',statistics.mean(Numlist));
print('Variance=',statistics.variance(Numlist));
print('Standard deviation=',statistics.stdev(Numlist));
Output:
Enter the value of n : 5
Enter number 1:10
Enter number 2:20
Enter number 3:30
Enter number 4:5
Enter number 5:15
The list of elements is [10, 20, 30, 5, 15]
Mean= 16
Variance= 92.5
Standard deviation= 9.617692030835672

Ans 2 (using user-defined functions):


import math
def mean(List):
return sum(List)/len(List)
def variance(List):
var_sum=0
mn=mean(List)
for num in List:
var_sum=var_sum+(num-mn)**2
return var_sum/len(List)

DSATM, Bangalore-82 Page 4


PYTHON PROGRAMMING LABORATORY 23PLCS21

def std_dev(List):
return math.sqrt(variance(List))
Numlist = []
n = int(input("Enter the value of n : "))
for i in range(0, n):
ele = int(input('Enter number '+ str(i+1)))
Numlist.append(ele)
print('The list is', Numlist)
print('mean is',mean(Numlist))
print('variance is',variance(Numlist))
print('Standard deviation is',std_dev(Numlist))

Output
Enter the value of n : 5
Enter number 1:5
Enter number 2:15
Enter number 3:10
Enter number 4:20
Enter number 5:30
The list is [5, 15, 10, 20, 30]
mean is 16.0
variance is 92.5
Standard deviation is 9.617692030835672

DSATM, Bangalore-82 Page 5


PYTHON PROGRAMMING LABORATORY 23PLCS21

b) Develop a python program to convert binary to decimal, octal to hexadecimal using


functions.
def BinToDec(b):
return int(b, 2)
bnum = input("Enter a Binary Number: ")
dnum = BinToDec(bnum)
print("Equivalent Decimal Value = ", dnum)
def OctToHex(o):
return hex(int(o, 8))
onum = input("Enter an Octal Number: ")
hnum = OctToHex(onum)
print("Equivalent Hexadecimal Value =", hnum[2:].upper())

Output
Enter a Binary Number: 10001
Equivalent Decimal Value = 17
Enter an Octal Number: 756
Equivalent Hexadecimal Value = 1EE
Ans 2:
def BinToDec(b):
try:
return int(b, 2)
except ValueError:
print('Not a valid binary number')
bnum = input("Enter the Binary Number: ")
dnum = BinToDec(bnum)
print("Equivalent Decimal Value = ", dnum)
def OctToHex(o):
try:
return hex(int(o, 8))
except ValueError:
print('Not a valid Octal number')
onum = input("Enter Octal Number: ")
hnum = OctToHex(onum)

DSATM, Bangalore-82 Page 6


PYTHON PROGRAMMING LABORATORY 23PLCS21

try:
print("\nEquivalent Hexadecimal Value =", hnum[2:].upper())
except TypeError:
print()
Output:
Enter the Binary Number: 45
Not a valid binary number
Equivalent Decimal Value = None
Enter Octal Number: 89
Not a valid Octal number

DSATM, Bangalore-82 Page 7


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-4
Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable messages.

Program:
input=str(input('Enter a string of digits: '))
List=['1','2','3','4','5','6','7','8','9','0']
for dig in List:
count=0
for character in input:
if dig==character:
count+=1
print('Number of ',dig, ': ' ,count)
Output:
Enter string: 12334545645768787989
Number of 1: 1
Number of 2: 1
Number of 3: 2
Number of 4: 3
Number of 5: 3
Number of 6: 2
Number of 7: 3
Number of 8: 3
Number of 9: 2
Number of 0: 0

DSATM, Bangalore-82 Page 8


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-5
a) Develop a program to print 10 most frequently appearing words in a text file. [Hint:
Use dictionary with distinct words and their frequency of occurrences. Sort the
dictionary in the reverse order of frequency and display dictionary slice of first 10
items]
fname=input('Enter file directory/name: ')
c=[]
d={}
with open(fname,'r') as f:
content=f.read()
word=content.split()
for i in word:

c.append(i)

for i in c:

count=0

for j in c:

if i==j:

count+=1

d[i]=count

sortd=sorted(d.items(), key=lambda x:x[1], reverse=True)


print(sortd[0:10])
Output
Enter file directory/name: input.txt
[('you', 3), ('To', 3), ('am', 2), ('very', 2), ('Geeky', 2), ('Hello', 1), ('there', 1), ('I', 1),
('happy', 1), ('to', 1)]

DSATM, Bangalore-82 Page 9


PYTHON PROGRAMMING LABORATORY 23PLCS21

b) Develop a program to sort the contents of a text file and write the sorted contents
into a separate text file. [Hint: Use string methods strip(), len(), list methods sort(),
append(), and file methods open(), read lines(), and write()].

fname=input('Enter file name/directory: ')


with open(fname,'r') as f:
read=f.read()
word=read.split()
l=[]
for i in word:
l.append(i)
l.sort()
wname=input('Enter file name to create: ')
with open(wname,'w') as w:
for j in l:
w.write(j)
w.write('\n')
OUTPUT:
Enter file name/directory: input.txt
Enter file name to create: aa.txt

DSATM, Bangalore-82 Page 10


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM - 6
a) Develop a program to backing up a given Folder (Folder in a current working
directory) into a ZIP File by using relevant modules and suitable methods.

import shutil
name=input('Enter zip file name: ')
directory=input('Enter file directory: ')
shutil.make_archive(name,'zip',directory)
Output
Enter zip file name: eggs
Enter file directory: eggs
'C:\\Users\\rama\\eggs.zip'

b) Write a function named DivExp which takes TWO parameters a, b and returns a
value c (c=a/b). Write suitable assertion for a>0 in function DivExp and raise an
exception for when b=0. Develop a suitable program which reads two values from
the console and calls a function DivExp.
import sys
def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
sys.exit(0)
else:
return c
val1 = int(input("Enter a value for a : "))
val2 = int(input("Enter a value for b : "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)

Run 1:
Enter a value for a : 10
Enter a value for b : 5
10 / 5 = 2.0
Run 2:
Enter a value for a : -1

DSATM, Bangalore-82 Page 11


PYTHON PROGRAMMING LABORATORY 23PLCS21

Enter a value for b : 20


Traceback (most recent call last):
File
"C:/Users/dilee/AppData/Local/Programs/Python/Python312/exception_assertion.py",
line 13, in <module>
val3 = DivExp(val1, val2)
File
"C:/Users/dilee/AppData/Local/Programs/Python/Python312/exception_assertion.py",
line 3, in DivExp
assert a>0, "a should be greater than 0"
AssertionError: a should be greater than 0

Run 3:
Enter a value for a : 20
Enter a value for b : 0
Value of b cannot be zero

DSATM, Bangalore-82 Page 12


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-7
a) Develop a Python program to demonstrate find all function and character class
using regex module.

Description of different character classes:


[abc] Match the letter a or b or c
[abc][pq] Match letter a or b or c followed by either p or q.
[^abc] Match any letter except a, b, or c (negation)
[0-9] Match any digit from 0 to 9. inclusive (range)
[a-z] Match any lowercase letters from a to z. inclusive (range)
[A-Z] Match any UPPERCASE letters from A to Z. inclusive (range)
[a-zA-z] Match any lowercase or UPPERCASE letter. inclusive (range)
[m-p2-8] Ranges: matches a letter between m and p and digits from 2 to 8, but
not p2
[a-zA-Z0-9_] Match any alphanumeric character

Metacharacters

Metacharacters are characters with a special meaning:


Character Description Example
[] A set of characters "[a-m]"
\ Signals a special sequence "\d"
. Any character (except newline character) "he..o"
^ Starts with "^hello"
$ Ends with "planet$"
* Zero or more occurrences "he.*o"
+ One or more occurrences "he.+o"
? Zero or one occurrences "he.?o"
{} Exactly the specified number of occurrences "he.{2}o"
| Either or "falls|stays"
() Capture and group

DSATM, Bangalore-82 Page 13


PYTHON PROGRAMMING LABORATORY 23PLCS21

Program

import re
input_str = "This is sample string1"
pattern="[i][a-z]" #try different character classes
result = re.findall(pattern, input_str)
print("Matching value", result)
Output
Matching value ['is', 'is', 'in']

b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected]).

import re
# Define the regular expression for phone numbers
phone_regex = re.compile(r'\+\d{12}')
# Define the regular expression for email addresses
email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')

# Open the file for reading


with open('example.txt', 'r') as f:
for line in f:
# Search for phone numbers in the line
phone_matches = phone_regex.findall(line)
for match in phone_matches:
print("Phone Number:", match)
# Search for email addresses in the line
email_matches = email_regex.findall(line)
# Print any email address matches found
for match in email_matches:
print("Email Address:", match)
Output
Phone Number: +919656795959
Email Address: [email protected]
Phone Number: +916738294120
Email Address: [email protected]

DSATM, Bangalore-82 Page 14


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-8
Define a function which takes TWO objects representing complex numbers and returns
new complex number with a addition of two complex numbers. Define a suitable class
‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.

class Complex():
def init (self, a, b):
self.real=a
self.imaginary=b

def add(self,C1):
temp=Complex(0, 0)
temp.real = self.real + C1.real;
temp.imaginary = self.imaginary + C1.imaginary;
return temp;
def displayComplex(self):
print(self.real,'+i',self.imaginary, sep="")
complexList = []
n=int(input('Enter the value of n: '))
if n>=2:
for i in range(n):
a=int(input('Enter real part of the complex number '+str(i+1)+':'))
b=int(input('Enter imaginary part of the complex number '+str(i+1)+':'))
Complex_Obj=Complex(a,b)
complexList.append(Complex_Obj)
print("\nEntered Complex numbers are : ")
for obj in complexList:
obj. displayComplex()
sumObj = Complex(0,0)
for obj in complexList:
sumObj=sumObj.add(obj)
print("\nSum of N complex numbers is", end = " ")

DSATM, Bangalore-82 Page 15


PYTHON PROGRAMMING LABORATORY 23PLCS21

sumObj.displayComplex()
else:
print('Invalid input. Enter number greater than 2')
Output
Enter the value of n: 2
Enter real part of the complex number 1:1
Enter imaginary part of the complex number 1:2
Enter real part of the complex number 2:2
Enter imaginary part of the complex number 2:4

Entered Complex numbers are :


1+i2
2+i4

Sum of N complex numbers is 3+i6

DSATM, Bangalore-82 Page 16


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-9
Develop a program that uses class Student which prompts the user to enter marks in
three subjects and calculates total marks, percentage and displays the score card
details. [Hint: Use list to store the marks in three subjects and total marks. Use
init () method to initialize name, USN and the lists to store marks and total, Use
getMarks() method to read marks into the list, and display() method to display the score
card details.].

class Student():
def init (self, name, usn):
self.name=name
self.usn=usn
self.marks=[]
self.subjects=[]
def enterMarks(self):
for i in range(3):
sub=input('Enter subject: ')
self.subjects.append(sub)
mark=int(input('Enter marks of %s in %s: '%(self.name,sub)))
self.marks.append(mark)
def total(self):
total=self.marks[0]+self.marks[1]+self.marks[2]
return total
def per(self):
per=(self.marks[0]+self.marks[1]+self.marks[2])/3
return per
def disp(self):
print(self.name,'USN:',self.usn,'got',self.marks,'in',self.subjects)
print('Total marks:',self.total())
print('Percentage:',self.per())
name=input('Enter name of student: ')
usn=input('Enter USN: ')
s1=Student(name,usn)

DSATM, Bangalore-82 Page 17


PYTHON PROGRAMMING LABORATORY 23PLCS21

s1.enterMarks()
s1.disp()
OUTPUT:
Enter name of student: ram
Enter USN: 122
Enter subject: maths
Enter marks of ram in maths: 12
Enter subject: science
Enter marks of ram in science : 13
Enter subject: physics
Enter marks of ram in physics: 11
ram USN: 122 got [12, 13, 11] in ['maths', 'science ', 'physics']
Total marks: 36
Percentage: 12.0

DSATM, Bangalore-82 Page 18


PYTHON PROGRAMMING LABORATORY 23PLCS21

PROGRAM-10
Develop a program to convert list and dictionary into NumPy array
Code to read input into the dictionary
import numpy
n = int(input("Enter number of elements to insert into the dictionary: "))
my_dict= {}
for x in range(n):
new_key =input('Enter new key: ')
new_value = input('Enter new value: ')
my_dict[new_key] = new_value
lst = []
n = int(input("Enter number of elements to insert into the list : "))
for i in range(0, n):
ele = int(input('Enter an item: '))
lst.append(ele)
lst_arr = numpy.array(lst)
dict_array = numpy.array(list(my_dict.items()))
print ("List: ", lst)
print ("List Array: ", lst_arr)
print ("Dictionary: ", my_dict)
print ("Dictionary Array: ", dict_array)
OUTPUT:
Enter number of elements to insert into the dictionary: 4
Enter new key: 1
Enter new value: ise
Enter new key: 2
Enter new value: cse
Enter new key: 3
Enter new value: mech
Enter new key: 4
Enter new value: civil
Enter number of elements to insert into the list : 6
Enter an item: 34
Enter an item: 12
Enter an item: 45
Enter an item: 12
Enter an item: 65
Enter an item: 78

DSATM, Bangalore-82 Page 19


PYTHON PROGRAMMING LABORATORY 23PLCS21

List: [34, 12, 45, 12, 65, 78]


List Array: [34 12 45 12 65 78]
Dictionary: {'1': 'ise', '2': 'cse', '3': 'mech', '4': 'civil'}
Dictionary Array: [['1' 'ise']
['2' 'cse']
['3' 'mech']
['4' 'civil']]

DSATM, Bangalore-82 Page 20

You might also like