0% found this document useful (0 votes)
7 views16 pages

Python Lab Manual

This document is a laboratory report for a Bachelor of Technology course in Electronics and Computer Science Engineering at Visvesvaraya Technological University, detailing various Python programming assignments. The report includes programs for tasks such as calculating student details, generating Fibonacci sequences, computing factorials, and handling file operations. It serves as an academic requirement for the second semester of the 2024-2025 academic year.

Uploaded by

harshavard2006
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)
7 views16 pages

Python Lab Manual

This document is a laboratory report for a Bachelor of Technology course in Electronics and Computer Science Engineering at Visvesvaraya Technological University, detailing various Python programming assignments. The report includes programs for tasks such as calculating student details, generating Fibonacci sequences, computing factorials, and handling file operations. It serves as an academic requirement for the second semester of the 2024-2025 academic year.

Uploaded by

harshavard2006
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/ 16

Visvesvaraya Technological University, Belagavi

POST GRADUATION CENTRE, KALABURAGI

BACHELOR OF TECHNOLOGY (B.Tech)


IN
Electronics and Computer Science Engineering

A
Laboratory Report on

Introduction to Python Programming (BPLCK205B)

Submitted as a part of Academic Requirement for Second Semester


By :
(USN: )

Department of Electronics and Computer science Engineering,


Post Graduation Centre, Visvesvaraya Technological University.

KALABURAGI
2024-2025
VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELAGAVI
CPGS, Kalaburagi

U.S.N: DATE:

CERTIFICATE

This is to certify that Mr./Ms.…………………………………………………..


Studying in the B.Tech of ECE ......SECOND ......................... Semester has successfully completed all the
Programs in…Introduction to Python Programming with subject code BPLCK205B as prescribed by the
Visvesvaraya Technological University, Belagavi CPGS Kalaburagi for the academic year 2024- 2025.

Faculty In-charge Program Coordinator

Examiners:

1. Internal Examiner 2.Internal Examiner


SL
INDEX Date Page no Sign
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
1 messages.

b. Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.
a. Develop a program to generate Fibonacci sequence of length (N). Read N from
2 the console.

b. Write a function to calculate factorial of a number. Develop a program to compute


binomial coefficient (Given N and R).
Read N numbers from the console and create a list. Develop a program to print mean,
3 variance and standard deviation with suitable messages.

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

Develop a program to print 10 most frequently appearing words in a text file.[Hint: Use
5 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]

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

7 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.

Write a function named Div Exp which takes TWO parameters a, b and returns a value c
8 (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 Div Exp.

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
9 ‘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: Use list to store the marks in three subjects and total marks. Use
10 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.]
1a. 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.

Program :

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


stUSN = input("Enter the USN of the student :")
stMarks1 = int(input("Enter marks in Subject1:"))
stMarks2 = int(input("Enter marks in Subject2:"))
stMarks3 = int(input("Enter marks in Subject3:"))

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 : Vivek
Enter the USN of the student : 3VY22CS005
Enter marks in Subject 1 :90
Enter marks in Subject 2 : 89
Enter marks in Subject 3 : 88 StudentDetails
=========================
Name : Vivek
USN : 3VY22CS005
Marks 1 : 90
Marks 2 : 89
Marks 3 : 88
Total : 267
Percent : 89.00
=======================

[VTU CPGS KALABURAGI] Page 1


1.b. Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.

Program:

from datetime import date


perName = input("Enter the name of the person : ")
perDOB = int(input("Enter hisyear of birth : "))
curYear = date.today().year
perAge = curYear - perDOB

if (perAge > 60):


print(perName, "aged", perAge, "years is a SeniorCitizen.")else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")

Output:

1. Enter the name of the person : Arya


Enter his year of birth : 2004
Arya aged 19 years is not a Senior Citizen.

2. Enter the name of the person : Bhagat sing


Enter his year of birth : 1920
Bhagat sing aged 103 years is a Senior Citizen

[VTU CPGS KALABURAGI] Page 2


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

Program :

num = int(input("Enter the Fibonacci sequence length to be generated : "))


firstTerm = 0
secondTerm = 1
print("The Fibonacci series with", num, "terms is :")
print(firstTerm, secondTerm, end=" ")
for i in range(2,num):
curTerm = firstTerm + secondTerm
print(curTerm, end=" ")
firstTerm = secondTerm
secondTerm = curTerm

OUTPUT:
Enter the Fibonacci sequence length to be generated : 8
The Fibonacci series with 8 terms is :
0 1 1 2 3 5 8 13

[VTU CPGS KALABURAGI] Page 3


2b. Write a function to calculate factorial of a number.
Develop a program to compute binomial coefficient (Given N and R).

def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
n = int(input("Enter the value of N : " ))
r = int(input("Enter the value of R (R cannot be negative or greater than N):"))
nCr = fact(n)/(fact(r)*fact(n-r))
print(n,'C',r," = ","%d"%nCr,sep="")

Output:

Enter the value of N : 5


Enter the value of R (R cannot be negative or greater than N):2
5C2 = 10

[VTU CPGS KALABURAGI] Page 4


3. Read N numbers from the console and create a list. Develop a program to print
mean, variance and standard deviation with suitable messages.

Program :

from math import sqrt


myList = [ ]
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
print('The length of list1 is', len(myList))
print('List Contents', myList)
total = 0
for elem in myList:
total += elem
mean = total / num
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
variance = total / num
stdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", "%.2f"%stdDev)

Output :

Enter the number of elements in your list : 5Enter the element : 65


Enter the element : 55
Enter the element : 75
Enter the element : 85
Enter the element : 95
The length of list1 is 5
List Contents [65, 55, 75, 85, 95]
Mean = 75.0
Variance = 200.0
Standard Deviation = 14.14

[VTU CPGS KALABURAGI] Page 5


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

Program :

num = input("Enter a number : ")


print("The number entered is :", num)
uniqDig = set(num)
for elem in uniqDig:
print(elem, "occurs", num.count(elem), "times")

OUTPUT

Enter a number : 2996665

The number entered is : 2996665


5 occurs 1 time
2 ocuurs 1 time
6 occurs 3 times
9 occurs 2 times

[VTU CPGS KALABURAGI] Page 6


5. 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 reverseorder of frequency and display dictionary slice of first 10 items]

Program :

import sys
import string
import os.path
fname = input("Enter the filename : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
filecontents = ""
for line in infile:
for ch in line:
if ch not in string.punctuation:
filecontents = filecontents + ch
else:
filecontents = filecontents + ' '
wordFreq = {}
wordList = filecontents.split()
for word in wordList:
if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1
sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )
print("\n===================================================")
print("10 most frequently appearing words with their count")
print("===================================================")
for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1], "times")

OUTPUT

vtu occurs 5 times


hi occurs 1 times
im occurs 1 times
kalaburagi occurs 1 times
cpgs occurs 1 times

[VTU CPGS KALABURAGI] Page 7


6. 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(), readlines(), and write()].

Program :

import os.path
import sys
fname = input("Enter the filename whose contents are to be sorted : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
myList = infile.readlines()
lineList = []
for line in myList:
lineList.append(line.strip())
lineList.sort()
outfile = open("sorted.txt","w")
for line in lineList:
outfile.write(line + "\n")
infile.close()
outfile.close()
if os.path.isfile("sorted.txt"):
print("\nFile containing sorted content sorted.txt created successfully")
print("sorted.txt contains", len(lineList), "lines")
print("Contents of sorted.txt")

print("================================================================")
rdFile = open("sorted.txt","r")
for line in rdFile:
print(line, end="")

OUTPUT:

Enter the filename whose contents are to be sorted : sorted.txt

File containing sorted content sorted.txt created successfully


sorted.txt contains 6 lines
Contents of sorted.txt
=================================================================
BEST
COLLEGE
ENGINEERNIGN
IS
THE
VTU

[VTU CPGS KALABURAGI] Page 8


7. 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.

Program :

import os
import zipfile

def backup_folder_to_zip(folder_name, zip_name):


# Create a full path for the ZIP file
zip_path = os.path.join(os.getcwd(), zip_name)

# Create a new ZIP file


with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Walk through the folder
for foldername, subfolders, filenames in os.walk(folder_name):
for filename in filenames:
# Create the full filepath
file_path = os.path.join(foldername, filename)
# Add file to ZIP file, preserving the folder structure
arcname = os.path.relpath(file_path, start=folder_name)
zipf.write(file_path, arcname)

print(f'Backup completed: {zip_path}')

# Example usage
folder_to_backup = 'your_folder_name' # Replace with your folder name
zip_file_name = 'backup.zip' # Replace with your desired zip file name

backup_folder_to_zip(folder_to_backup, zip_file_name)

Output:

Backup completed:
C:\Users\krcom\AppData\Local\Programs\Python\Python312\backup.zip

[VTU CPGS KALABURAGI] Page 9


8. 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.

Program :

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)

Output:

Enter a value for a : 6


Enter a value for b : 7
6 / 7 = 0.8571428571428571

[VTU CPGS KALABURAGI] Page 10


9. 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 .

Program :

class Complex:
def init (self, real, imag):
self.real=real
self.imag=imag
def add_complex(c1,c2):
real_part = c1.real + c2.real
imag_part = c1.imag + c2.imag
return Complex(real_part,imag_part)
c1 = Complex(2, 3)
c2 = Complex(4, 5)
result = add_complex(c1,c2)
print("sum of", c1.real, "+", c1.imag, "i and", c2.real, "+", c2.imag, "i is:", result.real, "+",
result.imag, "i")

OUTPUT :
sum of 2 + 3 i and 4 + 5 i is: 6 + 8

[VTU CPGS KALABURAGI] Page 11


10. 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 tostore 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.]

Program :

class Student:
def init (self, name = "", usn = "", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score

def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]

def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print(" %15s"%("NAME"), "%12s"%("USN"),
"%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL","%12s"%("PERCE
NTAGE"))
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn,
"%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.score[3],"%12.2f"%per
centage)
print(spcstr)

def main():
s1 = Student()
s1.getMarks()
s1.display()

main()

[VTU CPGS KALABURAGI] Page 12


Output :

Enter student Name : SUHANA


Enter student USN : 3VYCS001
Enter marks in Subject 1 : 45
Enter marks in Subject 2 : 68
Enter marks in Subject 3 : 90

========================================================================
SCORE CARD DETAILS
========================================================================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
===============================================================================
SUHANA 3VYCS001 45 68 90 203 67.67
===============================================================================

[VTU CPGS KALABURAGI] Page 13

You might also like