LatestPythonLabManual-2023 Batch

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Course Title: Introduction to Python Programming

Course Code: BPLCK105B/205B

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.

Print ("Enter the name")


Name=input ()
print("Enter the usn of student")
usn=input()
print("Enter the marks of first subject")
marks1=int(input())
print("Enter the marks of second subject")
marks2=int(input())
print("Enter the marks of third subject")
marks3=int(input())
total=marks1+marks2+marks3
percentage=total/3
print("-----------------Displaying student details---------")
print("Student Name",name)
print("Student USN",usn)
print("------------------Marks in three subjects-----------")
print("Marks of first subject:",marks1)
print("Marks of second subject",marks2)
print("Marks of third subject",marks3)
print("---------Displaying total marks and percentage of the student--
----------")
print("Total marks of the subject”, total)
print("Percentage of the student{:.2f}".format(percentage))

Output

****************************************************************
Enter the name
Jyothy
Enter the usn of student
1JT23CS001
Enter the marks of first subject
65
Enter the marks of second subject
70
Enter the marks of third subject
72
-----------------Displaying student details---------
Student Name Jyothy
Student USN 1JT23CS001
------------------Marks in three subjects-----------
Marks of first subject: 65
Marks of second subject: 70
Marks of third subject: 72
-----Displaying total marks and percentage of the student-------
Total marks of the subject 207
Percentage of the student 69.00

**********************************************************************

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.

print("Enter the name")


name=input()
print("Enter the year of birth of a person")
yob=int(input())
age=2023-yob
if age>=60:
print(name,"is a Senior citizen")
else:
print(name,"Not a Senior citizen")

Output

****************************************************************
Enter the name Enter the name
Jyothy Jyothy
Enter the year of birth Enter the year of birth
1990 1940
Jyothy Not a Senior citizen Jyothy is a Senior citizen
2.a) Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

n=int(input("Enter length of Fibonacci sequence"))


n1=0
n2=1
count=2
if n<0:
print("Enter only positive values")
elif n==1:
print(n1)
else:
print(n1,end='\t')
print(n2,end='\t')5
while count<n:
n3=n1+n2
print(n3,end='\t')
count=count+1
n1=n2
n2=n3
OR

num=int(input("enter the number"))


n1,n2=0,1
sum=0
if num<=0:
print("enter the number greater than 0")
else:
for i in range(0,num):
print(sum,end=" ")
n1=n2
n2=sum
sum=n1+n2

Output

****************************************************************
Enter length of Fibonacci sequence 10

0 1 1 2 3 5 8 13 21 34
2.b) Write a function to calculate factorial of a number. Develop a
program to compute binomial coefficient (Given N and R).

def find_factorial(number):
factorial=1
if(number<0):
print("Negative number cannot possible")
return

for i in range(1,number+1):
factorial=factorial*i
return factorial

number=int(input("Enter the number"))


factorial=find_factorial(number)
print("Factorial of",number,"is",factorial)

#Code to calculate binomial co-efficient


n=int(input("Enter the first positive ineteger"))
r=int(input("Enter the Second positive ineteger"))
print(N,'C',R,find_factorial(N)/(find_factorial(R)*find_factorial(N-R)))

Output

****************************************************************

Enter the number6


Facorial of 6 is 720
Enter the first positive ineteger5
Enter the Second positive ineteger3
5 C 3 10.0
3.Read N numbers from the console and create a list. Develop a program
to print mean, variance and standard deviation with suitable messages.

import math

# Read numbers from console and create a list


n = int(input("Enter the number of elements: "))
numbers = []
for i in range(n):
num = float(input(f"Enter element {i+1}: "))
numbers.append(num)

# Calculate mean
mean = sum(numbers) / n

# Calculate variance
variance = sum((x - mean) ** 2 for x in numbers) / n

# Calculate standard deviation


std_deviation = math.sqrt(variance)

# Print results
print("Numbers:", numbers)
print("Mean:", mean)
print("Variance:", variance)
print("Standard Deviation:", std_deviation)

Output

****************************************************************
Enter the number of elements: 5
Enter element 1: 3
Enter element 2: 6
Enter element 3: 9
Enter element 4: 12
Enter element 5: 15
Numbers: [3.0, 6.0, 9.0, 12.0, 15.0]
Mean: 9.0
Variance: 18.0
Standard Deviation: 4.242640687119285
4. Read a multi-digit number (as chars) from the console. Develop a
program to print the frequency of each digit with suitable message.

num=input("enter the number")


length=len(num)
print(length)
dt0=0;dt1=0;dt2=0;dt3=0;dt4=0;dt5=0;dt6=0;dt7=0;dt8=0;dt9=0
for i in range(length):
if(num[i]=='0'):
dt0=dt0+1
elif(num[i]=='1'):
dt1=dt1+1
elif(num[i]=='2'):
dt2=dt2+1
elif(num[i]=='3'):
dt3=dt3+1
elif(num[i]=='4'):
dt4=dt4+1
elif(num[i]=='5'):
dt5=dt0+1
elif(num[i]=='6'):
dt6=dt6+1
elif(num[i]=='7'):
dt7=dt7+1
elif(num[i]=='8'):
dt8=dt8+1
else:
dt9=dt9+1
freq=[dt0,dt1,dt2,dt3,dt4,dt5,dt6,dt7,dt8,dt9]
for i in range(10):
if freq[i]==0:
continue
print(i,"digit",freq[i],"times")

Output

****************************************************************
enter the number342111
6
1 digit 3 times
2 digit 1 times
3 digit 1 times
4 digit 1 times
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]

ifile=open("C:/Users/win-7/Documents/jit.txt")
dict_words={}
for line in ifile:
words=line.split()
for word in words:
dict_words[word]=dict_words.get(word,0)+1

list_words=[]
for key,val in dict_words.items():
list_words.append((val,key))
list_words.sort(reverse=True)
print("the slice of first 10 items of sorted dictionary are")
print(list_words[0:10])

Output

****************************************************************
jit.txt

The and and or operators always take two Boolean values (or
expressions),so considered binary operators. The and operator
evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.

****************************************************************

The slice of first 10 items of sorted dictionary are


[(3, 'and'), (2, 'values'), (2, 'to'), (2, 'evaluates'), (2, 'The'),
(2, 'Boolean'), (1, 'two'), (1, 'take'), (1, 'so'), (1, 'otherwise,')]

The code you provided reads a file named "jit.txt" located at


"C:/Users/win-7/Documents/" and creates a dictionary called
dict_words. It then iterates over each line in the file, splits the
line into words, and updates the count of each word in the
dictionary.

After that, it creates an empty list called list_words and iterates


over the key-value pairs in the dict_words dictionary. It
appends tuples of (value, key) to list_words, effectively
swapping the positions of the key and value. The purpose is to
sort the list based on the values (word counts) in descending
order.

Finally, it sorts list_words in reverse order and prints the first


10 items, which represent the most frequently occurring words
in the file.
However, please note that the code provided is missing the
closing of the file. You should add ifile.close() after the for loop
to close the file.
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()].

ifile=open("C:/Users/win-7/Documents/jit.txt")
ofile=open("C:/Users/win7/Documents/jit1.txt",mode=’w’)
word_list=[]
for line in ifile:
words=line.split()
for word in words:
word_list.append(word)
word_list.sort()
print(word_list)
for word in word_list:
ofile.write(word +" ")
ofile.close()

Output

****************************************************************
Jit8.txt

['and', 'and', 'and', 'and', 'are', 'cpu', 'cpu', 'it',


'it', 'lol', 'lol', 'oops', 'or', 'or', 'or', 'or',
'or', 'or', 'or', 'or', 'or', 'ram', 'ram', 'the',
'you', 'you']
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.

def DivExp(a,b):
try:
assert a>0
if b==0:
raise ZeroDivisionError
c=a/b
return c
except ZeroDivisionError:
print("zero division error")

except AssertionError:
print("Assertion failure: number is negative ")
a=int(input("enter a value"))
b=int(input("enter b value"))
result=DivExp(a,b)
print(result)

Output

****************************************************************

Enter a value 10
Enter b value 5
2.0
Enter a value -1
Enter b value 5
Assertion failure: number is negative
None
Enter a value 5
Enter b value 0
Zero division error
None
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:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total_marks = 0

def getMarks(self):
for i in range(3):
mark = float(input("Enter marks for subject {}:".format(i+1)))
self.marks.append(mark)
self.total_marks += mark

def display(self):
print("Name:",self.name)
print("USN:",self.usn)
print("Marks:",self.marks)
print("Total Marks:",self.total_marks)
percentage=(self.total_marks / 3)
print("Percentage:",percentage)
# Main program
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")

student = Student(name, usn)


student.getMarks()
student.display()
Output

****************************************************************
Enter student's name: jyothy
Enter student's USN: 1bg11cs421
Enter marks for subject 1:88
Enter marks for subject 2:56
Enter marks for subject 3:77
Name: Jyothy
USN: 1bg11cs421
Marks: [88.0, 56.0, 77.0]
Total Marks: 221.0
Percentage: 73.66666666666667

In this program, the Student class is defined with an __init__


method that initializes the name, usn, marks, and total_marks
attributes. The getMarks method prompts the user to enter marks
for each subject, stores them in the marks list, and calculates the
total_marks. The display method prints the student's name,
USN, marks, total marks, and percentage.
In the main program, the user is prompted to enter the student's
name and USN. Then, a Student object is created with the
provided name and USN. The getMarks method is called to
input the marks, and finally, the display method is called to print
the scorecard details including the percentage.
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.

import os,sys,zipfile
print(os.getcwd())
foldername=input("enter the folder name")
if(os.path.exists(os.getcwd()+"//"+foldername)):
zipfilename=input("enter the zip filenmae .zip")
zf=zipfile.ZipFile(zipfilename,"w")
for dirname,subdirs,files in os.walk(foldername):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname,filename))
zf.close()
if(os.path.exists(os.getcwd()+"//"+zipfilename)):
print("zip file created sucessfully")
else:
print("zip not creates")

else:
print("file does not exists")
sys.exit(0)

Output

****************************************************************
enter the folder name:test
enter the zip filenmae .zip:test1.zip
zip file created successfully
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.

import sys
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary

def add(self, other):


real_sum = self.real + other.real
imag_sum = self.imaginary + other.imaginary
return Complex(real_sum, imag_sum)
def read_complex():
real = float(input("Enter the real part: "))
imaginary = float(input("Enter the imaginary part: "))
return Complex(real, imaginary)

N = int(input("Enter the number of complex numbers (N >= 2): "))

if N < 2:
print("Please enter a valid value for N (N >= 2).")
sys.exit("error")

complex_numbers = []
for i in range(N):
print(f"Enter complex number {i+1}:")
complex_number = read_complex()
complex_numbers.append(complex_number)

# Compute the sum of N complex numbers


sum_complex = complex_numbers[0]
for i in range(1, N):
sum_complex =sum_complex.add(complex_numbers[i])

print("Sum of the complex numbers is:",sum_complex.real, "+", sum_complex.imaginary, "i")

Output

****************************************************************

Enter the number of complex numbers (N >= 2): 3


Enter complex number 1:
Enter the real part: 4
Enter the imaginary part: 5
Enter complex number 2:
Enter the real part: 3
Enter the imaginary part: 6
Enter complex number 3:
Enter the real part: 2
Enter the imaginary part: 7
Sum of the complex numbers is: 9.0 + 18.0 i

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy