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

Python Lab Manual

The document provides information about an introduction to Python programming course including the course code, department, and list of programming exercises to be completed as part of the course. The exercises cover topics like reading input, working with lists, files, classes and more.

Uploaded by

VRUSHANK M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Python Lab Manual

The document provides information about an introduction to Python programming course including the course code, department, and list of programming exercises to be completed as part of the course. The exercises cover topics like reading input, working with lists, files, classes and more.

Uploaded by

VRUSHANK M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

SAMBHRAM INSTITUTE OF TECHNOLOGY

(Affiliated to Visvesvaraya Technological University, Belgaum)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INTRODUCTION TO PYTHON PROGRAMMING

Sub Code: BPLCK205B

For
B E- II Semester [2022 Scheme]
SAMBHRAM INSTITUTE OF TECHNOLOGY
(Affiliated to Visvesvaraya Technological University, Belgaum)

Department of Computer Science and Engineering

LAB MANUAL
For
B.E II - SEMESTER LAB

NAME: …………………………………………………………………….

USN………………………………………………………………………….

BRANCH: ………………………………….. SECTION: …………


Programming Exercises
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.
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.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
b. Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
3. Read N numbers from the console and create a list. Develop a program to print mean, 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.
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 reverse order of
frequency and display dictionary slice of first 10 items]
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()].
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.
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.
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.
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 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.]
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.

defprintResult():
total=(int)(subject1 + subject2 + subject3)
percentage = (int)( (subject1 + subject2 +subject3) / 300 * 100 );
print("USN Name total percentage")
print(usn,"\t",name,"\t",total,"\t",percentage)
if percentage<35:
print("student",name , "has failed")
else:
print("Student",name, "has passed")
usn=input("Enter USN : ")
name = input("Enter Name : ")
subject1 =int(input("Enter subject1 marks : "))
subject2 =int(input("Enter subject2 Marks : "))
subject3 = int(input("Enter subject3 Marks : "))

print("Result : ")
printResult()

OUTPUT1:
Enter USN : 12
Enter Name : Mark
Enter subject1 marks : 87
Enter subject2 Marks : 66
Enter subject3 Marks : 55
Result :
USN Name total percentage
12 Mark 208 69
Student Mark has passed

OUTPUT2:
Enter USN : 11
Enter Name : James
Enter subject1 marks : 23
Enter subject2 Marks : 11
Enter subject3 Marks : 15
Result :
USN Name total percentage
11 James 49 16
Student James has failed
1b)Develop a program to read the name and year of birth of a person. Display whether the
person is asenior citizen or not.

class Person:
defgetPersonDetails(self):
self.name=input("Enter Name : ")
self.year = int(input("Enter year : "))

defprintResult(self):
self.age=(int)(2023-self.year)
print(self.age,"year")
if self.age>65:
print("Person",self.name , "is senior citizen")
else:
print("Person",self.name , "is not a senior citizen")

S1=Person()
S1.getPersonDetails()

print("age is : ")
S1.printResult()

OUTPUT1:
Enter Name : Spencer
Enter year : 2020
age is :
3 year
Person Spencer is not a senior citizen

OUTPUT2:
Enter Name : Scott
Enter year : 1945
age is :
78 year
Person Scott is senior citizen
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.

nterms = int(input("Enter N? "))


n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms<= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elifnterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count <nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

OUTPUT:
Enter N? 5
Fibonacci sequence:
0
1
1
2
3
2.b. Write a function to calculate factorial of a number. Develop a program to compute
binomialcoefficient (Given N and R).

defbinomialCoeff(n, k):
if k > n:
return 0
if k == 0 or k == n:
return 1
# Recursive Call
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)

n= int(input("Enter a number N: "))


k=int(input("Enter value of K: "))
factorial = 1
if n < 0:
print(" Factorial does not exist for negative numbers")
elif n== 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
print("Value of C(%d,%d) is (%d)" % (n, k, binomialCoeff(n, k)))

OUTPUT:
Enter a number N: 5
Enter value of K: 2
The factorial of 5 is 120
Value of C(5,2) is (10)
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance andstandard deviation with suitable messages.

import numpy as np
lst = []
# number of elements as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
lst.append(ele) # adding the element
print("list elements are",lst)
print("mean is" ,np.average(lst))
print("variance is" ,np.var(lst))
print("standars deviation is",np.std(lst))

OUTPUT:
Enter number of elements : 5
1
2
3
4
5
list elements are [1, 2, 3, 4, 5]
mean is 3.0
variance is 2.0
standars deviation is 1.4142135623730951
4. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency ofeach digit with suitable message.

defchar_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
str1=input("Enter the multi-digit number: ")
print(char_frequency(str1))

OUTPUT:
Enter the multi-digit number: 55667888
{'5': 2, '6': 2, '7': 1, '8': 3}
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
reverse order offrequency and display dictionary slice of first 10 items]
text =open("sample.txt", "r")

# Create an empty dictionary


d =dict()

# Loop through each line of the file


forline intext:
# Remove the leading spaces and newline character
line =line.strip()

# Convert the characters in line to


# lowercase to avoid case mismatch
line =line.lower()

# Split the line into words


words =line.split(" ")

# Iterate over each word in line


forword inwords:
# Check if the word is already in dictionary
ifword ind:
# Increment count of word by 1
d[word] =d[word] +1
else:
# Add the word to dictionary with count 1
d[word] =1

# Print the contents of dictionary


forkey inlist(d.keys()):
print(key, ":", d[key])
OUTPUT:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
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()].

def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort()
outfile = open("result.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample.txt")
7. Develop a program to backing Up a given Folder (Folder in a current working directory) into
a ZIPFile by using relevant modules and suitable methods.

from zipfile import ZipFile


import os
defget_all_file_paths(directory):
# initializing empty file paths list
file_paths = []

# crawling through directory and subdirectories


for root, directories, files in os.walk(directory):
for filename in files:
# join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath)

# returning all file paths


return file_paths

def main():
# path to folder which needs to be zipped
directory = './python_files'

# calling function to get all file paths in the directory


file_paths = get_all_file_paths(directory)
# printing the list of all files to be zipped
print('Following files will be zipped:')
for file_name in file_paths:
print(file_name)
# writing files to a zipfile
with ZipFile('my_python_files.zip','w') as zip:
# writing each file one by one
for file in file_paths:
zip.write(file)
print('All files zipped successfully!')
if __name__ == "__main__":
main()

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.

defDivExp(a,b):
try:
c=a/b
print("Quotient:",c)
except ZeroDivisionError:
print("Division by Zero!")
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
result=(DivExp(a,b))

OUTPUT:
Enter the value of a:5
Enter the value of b:0
Division by Zero!
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.

class Complex:

# Constructor to accept
# real and imaginary part
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;

# Defining addComp() method


# for adding two complex number
defaddComp(self, C1, C2):

# creating temporary variable


temp=Complex(0, 0)

# adding real part of complex numbers


temp.real = C1.real + C2.real;

# adding Imaginary part of complex numbers


temp.imaginary = C1.imaginary + C2.imaginary;

# returning the sum


return temp;

# Driver code
if __name__=='__main__':

# First Complex number


C1 = Complex(3, 2);
# printing first complex number
print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary))

# Second Complex number


C2 = Complex(9, 5);

# printing second complex number


print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary))

# for Storing the sum


C3 = Complex(0, 0)

# calling addComp() method


C3 = C3.addComp(C1, C2);

# printing the sum


print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary))

OUTPUT:
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7
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 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:
defgetStudentDetails(self):
self.usn=input("Enter USN : ")
self.name = input("Enter Name : ")
self.subject1 =int(input("Enter subject1 marks : "))
self.subject2 = int(input("Enter subject2 Marks : "))
self.subject3 = int(input("Enter subject3 Marks : "))
defprintResult(self):
self.total=(int)(self.subject1 + self.subject2 + self.subject3)
self.percentage = (int)( (self.subject1 + self.subject2 + self.subject3) / 300 * 100 );
print("USN Name total percentage")
print(self.usn,self.name,self.total,self.percentage)
if self.percentage<35:
print("student",self.name , "has failed")
else:
print("Student",self.name, "has passed")
S1=Student()
S1.getStudentDetails()
print("Result : ")
S1.printResult()
OUTPUT1:
Enter USN : 12
Enter Name : Mark
Enter subject1 marks : 87
Enter subject2 Marks : 66
Enter subject3 Marks : 55
Result :
USN Name total percentage
12 Mark 208 69
Student Mark has passed

OUTPUT2:
Enter USN : 11
Enter Name : James
Enter subject1 marks : 23
Enter subject2 Marks : 11
Enter subject3 Marks : 15
Result :
USN Name total percentage
11 James 49 16
student James has failed

You might also like