[go: up one dir, main page]

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

BPLCK205B Lab Programs

The document outlines a series of programming exercises that involve reading student details, calculating marks, generating Fibonacci sequences, computing binomial coefficients, and analyzing data sets for mean, variance, and standard deviation. It also includes tasks for file handling, such as counting word frequencies, sorting file contents, and creating ZIP archives. Additionally, it covers exception handling, complex number operations, and the use of classes to manage student information.

Uploaded by

varunsugandhi0
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)
46 views16 pages

BPLCK205B Lab Programs

The document outlines a series of programming exercises that involve reading student details, calculating marks, generating Fibonacci sequences, computing binomial coefficients, and analyzing data sets for mean, variance, and standard deviation. It also includes tasks for file handling, such as counting word frequencies, sorting file contents, and creating ZIP archives. Additionally, it covers exception handling, complex number operations, and the use of classes to manage student information.

Uploaded by

varunsugandhi0
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

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.

#student details
name=input('enter the name of the student : ')
usn=input('enter the usn of the student : ')
m1=int(input('enter the marks of sub1: '))
m2=int(input('enter the marks of sub2: '))
m3=int(input('enter the marks of sub3: '))
total = m1+m2+m3
per = total/3
print('Student details ')
print('name : ',name)
print('usn : ',usn)
print('Marks of sub1 : ',m1)
print('Marks of sub2 : ',m2)
print('Marks of sub3 : ',m3)
print('total marks is: ',total)
print('percentage is : ',per)

Save the file as filename.py


For compilation and execution
C:\py2sem>python studetails.py
OUTPUT
enter the name of the student : Surya
enter the usn of the student : 1MP23AD0089
enter the marks of sub1: 78
enter the marks of sub2: 89
enter the marks of sub3: 92

Student details
name : Surya
usn : 1MP23AD0089
Marks of sub1 : 78
Marks of sub2 : 89
Marks of sub3 : 92
total marks is: 259
percentage is : 86.33333333333333

BGSCET 1
Program 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.
#senior citizen or not
from datetime import date
name = input('enter the name :')
yob = int(input('enter the year of birth :'))
cyear = date.today().year
age =cyear - yob
if age >= 60 :
print('senior citizen')
else :
print('Not a senior citizen')

Save the file lab1b.py


For compilation and execution
C:\py2sem>python lab1b.py
OUTPUT 1
enter the name :sony
enter the year of birth :1994
Not a senior citizen
OUTPUT 2
enter the name :Venu
enter the year of birth :1964
senior citizen
Program 2:
a..Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

#fibonacci sequence
n=int(input( 'enter the number of terms :'))
f1=0
f2=1
print('fibinacci sequence')
print(f1)
print(f2)
for i in range(2,n):
f3=f1 +f2
print(f3)
f1=f2
f2=f3

BGSCET 2
OUTPUT
enter the number of terms :7
fibinacci sequence
0
1
1
2
3
5
8

Program 2:
b. Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R)
formula to calculate ncr = n!/(r! - (n-r)!)
#function
def fact(n):
f=1
for i in range(1,n + 1):
f=f*i
return f
#main program to find n c r
n= int(input('enter the value of n '))
r= int(input('enter the value of r '))
ncr = fact(n) / (fact(r)* fact(n-r))
print('ncr value is ',ncr).
import java.util.Scanner;

OUTPUT
enter the value of n 5
enter the value of r 3
ncr value is 10.0

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

Example
Consider the data set: 4, 8, 6, 5, 3, 9.
Step 1: Calculate the Mean
 Add up all the numbers: 4 + 8 + 6 + 5 + 3 + 9 = 35.
 Divide by the number of values (6): 35 / 6 = 5.83.
 mean is 5.83.
Step 2: Calculate the Variance
Subtract the mean from each number, square the result, and find the average:
 (4 – 5.83)² + (8 – 5.83)² + (6 – 5.83)² + (5 – 5.83)² + (3 – 5.83)² + (9 – 5.83)²
 = 3.35 + 4.68 + 0.03 + 0.69 + 8.00 + 10.03 = 26.78.
 Then, divide by 6: 26.78 / 6 = 4.80.
 ariance is 4.80.
Step 3: Calculate the Standard Deviation
 Take the square root of the variance: √4.80 = 2.19.
 So, the standard deviation is 2.19.

Program
#to calculate mean, variance and standard deviation
import math
L1 = [ ]
N= int(input("Enter the number of elements in list : "))
for i in range(N):
x = int(input("Enter the element : "))
L1.append(x)
print('List Contents :',L1)
total = 0
for i in range(N):
total =total + L1[i]

mean = total / N

sum=0
for i in range(N):
sum = sum + (L1[i] - mean) ** 2

variance = sum/N
stDev = math.sqrt(variance)

print("Mean =", mean)


print("Variance =", "%.2f"%variance)
print("Standard Deviation =", "%.2f"%stDev

BGSCET 4
OUTPUT

Enter the number of elements in list : 6


Enter the element : 4
Enter the element : 5
Enter the element : 6
Enter the element : 2
Enter the element : 1
Enter the element : 3
List Contents : [4, 5, 6, 2, 1, 3]
Mean = 3.5
Variance = 2.92
Standard Deviation = 1.71

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

#to check the frequency of each digit


num=input('enter the number as string ')
d1={ }
for c in num:
d1.setdefault(c,0)
d1[c]=d1[c] +1
print(‘d1)
for k, v in d1.items():
print(k , 'occurs ', v ,'times')

OUTPUT

enter the number as string 14432235


Dictionary contains {'1': 1, '4': 2, '3': 2, '2': 2, '5': 1}
1 occurs 1 times
4 occurs 2 times
3 occurs 2 times
2 occurs 2 times
5 occurs 1 times

BGSCET 5
Program 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]

# to display the frequncy of words ina file

f=open('example.txt', 'r')

txt = f.read()

print('contents of the file',txt)

words = txt.split()

print('words in the file ',words)

d1 = {}

for w in words:

d1.setdefault(w,0)

d1[w] = d1[w]+ 1

L1=[]

for k,v in d1.items():

L1.append([v,k])

L1.sort(reverse =True)

print('ferquency of words ')

for i in range(10):

print(L1[i])

Before executing the program

Note :Create a text file example.txt which contains(any data) in the same directory where python
program is saved otherwise need to specify the path of the file while reading the file
example.txt
object-oriented
Python is an interpreted
high-level programming language Python is
with dynamic semantics Python
Its high-level built in data structures Python is

BGSCET 6
OUTPUT
contents of the file object-oriented
Python is an interpreted
high-level programming language Python is
with dynamic semantics Python
Its high-level built in data structures Python is

words in the file ['object-oriented', 'Python', 'is', 'an', 'interpreted', 'high-level', 'programming', 'language',
'Python', 'is', 'with', 'dynamic', 'semantics', 'Python', 'Its', 'high-level', 'built', 'in', 'data', 'structures', 'Python',
'is']
ferquency of words
[4, 'Python']
[3, 'is']
[2, 'high-level']
[1, 'with']
[1, 'structures']
[1, 'semantics']
[1, 'programming']
[1, 'object-oriented']
[1, 'language']
[1, 'interpreted']

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

# to sort the contents of the file


f1 = open("example.txt", "r")
L1 = f1.readlines()

#Remove trailing \n characters


lineList = []
for line in L1:
lineList.append(line.strip())

lineList.sort()
# Write sorted contents to new file sorted.txt
f2= open('sorted.txt', 'w')
for line in lineList:
f2.write(line + '\n')

f1.close() # Close the input file


f2.close() # Close the output file

print('sorted file contains', len(lineList), 'lines')


print('Contents of sorted.txt')
f3 = open('sorted.txt', 'r')
for line in f3:
print(line)

BGSCET 8
example.txt
object-oriented
Python is an interpreted
high-level programming language Python is
with dynamic semantics Python
Its high-level built in data structures Python is

OUTPUT
sorted file contains 5 lines
Contents of sorted.txt
Its high-level built in data structures Python is

Python is an interpreted

high-level programming language Python is

object-oriented

with dynamic semantics Python

Program 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.
#creating a zipfile for the folder
import zipfile,os
zobj=zipfile.ZipFile('s4.zip','w')
for folder,subfolder,filename in os.walk('c:\\demo1'):
for fn in filename:
fpath=os.path.join(folder,fn)
zobj.write(fpath)
zobj.close()
if os.path.exists('s4.zip'):

BGSCET 9
print('zip file created')
else:
print('zip file not created')

INPUT:
Before executing create the following directory structure

c:\\demo1

c:\

demo1

sample1.txt

sample2.txt

demo2

demo3

sample4.txt

sample5.txt

sample6.txt

BGSCET 10
If the current working directory is c:\py2sem

c:\

py2sem

s4.zip

BGSCET 11
OUTPUT
zip file created

note :check the zip file under the current working directory with the name s4.zip

Program 8:

Write a function named DivExp which takes TWO parameters a, b and returns a value c (c=a/b). Writesuitable
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.

# assert and raising exception for division


def DivExp(a,b):
try:
assert a > 0,'value of a must be greater than 0'
if b== 0 :
raise Exception('value of b is zero')
c = a/b
return c
except (Exception,AssertionError) as err:
print(err)
a=int(input('enter the value of a '))
b=int(input('enter the value of b '))
print('result is ' ,DivExp(a,b) )

BGSCET 12
OUTPUT 1
enter the value of a -3
enter the value of b 5
value of a must be greater than 0
result is None

OUTPUT 2
enter the value of a 5
enter the value of b 2
result is 2.5

OUTPUT 3
enter the value of a 6
enter the value of b 0
value of b is zero
result is None

Program 9:
Define a function which takes TWO objects representing complex numbers and returns new complexnumber
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.

# to find the sum of complex numbers


class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def add_complex(x, y):
z=Complex(0,0)
z.real = x.real + y.real
z.imag = x.imag + y.imag
return z
N = int(input("Enter the number of complex numbers to add: "))

BGSCET 13
sum = Complex(0,0)
for i in range(N):
real = int(input("Enter the real part of the complex number: "))
imag = int(input("Enter the imaginary part of the complex number: "))
sum = add_complex(sum, Complex(real, imag))
print("The sum of complex numbers is: ", sum.real, "+", sum.imag, "i")

OUTPUT
Enter the number of complex numbers to add: 4

Enter the real part of the complex number: 3

Enter the imaginary part of the complex number: 4

Enter the real part of the complex number: 3

Enter the imaginary part of the complex number: 4

Enter the real part of the complex number: 3

Enter the imaginary part of the complex number: 5

Enter the real part of the complex number: 2

Enter the imaginary part of the complex number: 1

The sum of complex numbers is: 11 + 14 i

Program 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 storemarks and total,
Use getMarks() method to read marks into the list, and display() method to display the score card details.]

# student details using class concept

class Student():

def __init__(self, name, usn):

self.name=name

self.usn=usn

self.marks=[]

self.total_marks=0

BGSCET 14
def getMarks(self):

print('enter 3 subject marks ')

for i in range(3):

m=int(input())

self.marks.append(m)

self.total_marks=self.total_marks + m

def display(self):

print('name :',self.name)

print('USN :',self.usn)

print('marks :',self.marks)

print('Total marks :',self.total_marks)

print('percentage :',self.total_marks/3)

name=input('Enter name of student: ')

usn=input('Enter USN: ')

s1=Student(name,usn)

s1.getMarks()

s1.display()

OUTPUT
Enter name of student: Sachin
Enter USN: 1MP25CG112
enter 3 subject marks
68
91
54
name : Sachin
USN : 1MP25CG112
marks : [68, 91, 54]
Total marks : 213
percentage : 71.0

BGSCET 15
BGSCET 16

You might also like