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

Updated Python Manual2024-25

The document contains various Python lab programs that demonstrate different functionalities, including reading student details, calculating Fibonacci sequences, computing factorials, and handling complex numbers. It also includes programs for statistical calculations, file operations, and exception handling. Each program is accompanied by code snippets and example outputs to illustrate their functionality.

Uploaded by

qureshifahad0613
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)
2 views

Updated Python Manual2024-25

The document contains various Python lab programs that demonstrate different functionalities, including reading student details, calculating Fibonacci sequences, computing factorials, and handling complex numbers. It also includes programs for statistical calculations, file operations, and exception handling. Each program is accompanied by code snippets and example outputs to illustrate their functionality.

Uploaded by

qureshifahad0613
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/ 15

Python lab programs

1.a Develop a python code to read student details like name, usn, marks in three subjects and Display
the results like total_marks and percentage, with suitable messages

CODE:
name= input("Student please enter your name : ")

usn= input("Student please enter your usn : ")

s1=int(input("Student please enter your s1 marks : "))

s2=int(input("Student please enter your s2 marks : "))

s3=int(input("Student please enter your s3 marks : "))

totalmarks=s1+s2+s3

percentage=totalmarks/3

print("Student name : ",name)

print("Student usn : ",usn)

print("Student total_marks : ",totalmarks)

print("Student percentage : ",percentage)

................................................................................................................................................................

Program Output

Student please enter your name : Ali

Student please enter your usn : 24saec1234

Student please enter your s1 marks : 99

Student please enter your s2 marks : 98

Student please enter your s3 marks : 99

Student name : Ali

Student usn : 24saec1234

Student total_marks : 296

Student percentage : 98.66666666666667


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.

CODE:
personName = input("Enter the person name: ")
personYOB=int(input("Enter your birth year:"))
currentYear = int(input("Enter the Current Year: "))
if currentYear-personYOB >= 60:
print(personName,"is a senior person...")
else:
print(personName,"is not a senior person...")

................................................................................................................................................................

Program output1

Enter the person name: Ramesh

Enter your birth year : 1990

Enter current year : 2024

Ramesh is not a senior citizen

................................................................................................................................................................

Program output2

Enter the person name:: Suresh

Enter your birth year : 1940

Enter current year : 2024

Suresh is a senior citizen


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

CODE:

nterms= int(input("How many terms the user wants to print?"))

# First two terms


n1 =0
n2 =1
count=0
#Now, we will check if the number of terms is valid or not
if nterms <= 0:
print("Please enter a positive integer, the given number is not valid")
# if there is only one term, it will return n_1
elif nterms==1:
print("The Fibonacci sequence of the numbers upto", nterms,":")
print(n1)
#Then we will generate Fibonacci sequence of number
else:
print("The Fibonacci sequence of the numbers is:")
while count < nterms:
print(n1)
nth=n1+n2
#Atlast, we will update values
n1 = n2
n2 = nth
count+=1
Program output

How many terms the user wants to print?8


The Fibonacci sequence of the numbers is:

0
1
1
2
3
5
8
13
2.b Write a function to calculate factorial of a number.

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

OUTPUT 1:
Enter a number: 4

The factorial of 4 is 24

OUTPUT 2:
Enter a number: 0
The factorial of 0 is 1

OUTPUT 3:
Enter a number: -4
Factorial does not exist for negative numbers
2.c Python program to compute binomial coefficient (Given N and R).

CODE:

import math

def binomial_coefficient( n, r ):

if r > n:

return 0

else:

return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

n = int(input("Enter the value of n : "))

r = int(input("Enter the value of r : "))

result = binomial_coefficient(n, r)

print("The binomial coefficient is” ,result)

................................................................................................................................................................

Program output

Enter the value of n : 5

Enter the value of r : 2

The binomial coefficient C(5, 2) is 10

................................................................................................................................................................

Enter the value of n : 8

Enter the value of r : 10

The binomial coefficient C(8, 10) is 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.

CODE:

import numpy as np
#creating an empty list
list = [ ]
#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())
list.append(ele) #adding the element

print(list)
#Calculating mean using mean()
print(np.mean(list))
#Calculating variance using var()
print(np.var(list))
#Calculating standard deviation using std()
print(np.std(list))

OUTPUT:
Enternumberofelements:8
2
4
4
4
5
5
7
9

[2,4,4,4,5,5,7,9]

5.0

4.0

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

CODE:

def count_digits():

num = input("Enter a number: ")

if not num.isdigit():

print("Error: Only digits allowed.")

else:

unique_digits = []

for digit in num:

if digit not in unique_digits:

unique_digits.append(digit)

print("Digit " + digit + ": " + str(num.count(digit)) + " time(s)")

count_digits()

................................................................................................................................................................
program output
Enter a number: 35354353555
Digit 3: 4 time(s)
Digit 5: 6 time(s)
Digit 4: 1 time(s)
................................................................................................................................................................
Enter a number: 6786869980808088084
Digit 6: 3 time(s)
Digit 7: 1 time(s)
Digit 8: 8 time(s)
Digit 9: 2 time(s)
Digit 0: 4 time(s)
Digit 4: 1 time(s)
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]

CODE:

from collections import Counter

import re

words = []

with open('text.txt', 'r') as f:

for line in f:

# Remove punctuation marks from the line

line = re.sub(r'[^\w\s]', '', line)

words.extend(line.split())

count = Counter(words)

top10 = count.most_common(10)

print(top10)

................................................................................................................................................................

Note :Create a text file with name text.txt and write this content into that file

"Hello world, this is a test.

Hello again, how are you?

You are doing great, hello!

Test is going well, hi!

Hi, hello, how are you?

This is another test, hello.

Hello world, you are amazing.

Amazing test, hello again.

Again and again, hello.

Hello, hi, how are you?"


.............................................................................................................................................................

Output

[('are', 5), ('hello', 5), ('Hello', 4), ('you', 4), ('is', 3), ('test', 3), ('again', 3), ('how', 3), ('world', 2),

('hi',2)]

................................................................................................................................................................
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()].

CODE:

bands = []
filename = 'bands.txt'
with open(filename) as fin:
for line in fin:
bands.append(line.strip())
bands.sort(key=int)
print(bands)
filename = 'sorted.txt'
with open(filename, 'w') as fout:
for band in bands:
fout.write(band + '\n')
................................................................................................................................................................
Note : This program requires two text files ,these files must be created before execution of this

python program.First text file , it is an input file for python program , and copy and paste below content
into band.txt file.

band.txt

11

Second text file, it is an output file

11
# 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

Code:
import os
from zipfile import ZipFile
import shutil
def backup_folder(folder_name):
# Check if folder exists
if os.path.exists(folder_name):
# Create a ZIP file with the same name as the folder
zip_file_name = folder_name + '.zip'
# Use shutil.make_archive to create a ZIP archive
shutil.make_archive(folder_name, 'zip', folder_name)
print(f'Folder {folder_name} backed up to {zip_file_name}')
else:
print(f'Folder {folder_name} does not exist')
# Example usage
folder_name = 'abcd'
backup_folder(folder_name)
.....................................................................................................................................................
Output:
Note :
This progrm requires one input as a folder , here i have created folder with name ‘abcd’

this abcd folder is a input to this program.


(Note: abcd folder has to be created in the same folder where you have written your python
program)

After execution of this program , you will get output as zip folder with name ‘abcd.zip
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.

CODE:

def DivExp(a, b):

assert a > 0, "Dividend must be positive."

if b == 0:

print("Divide by zero error.")

return None

return a / b

n1 = float(input("Enter first number: "))

n2 = float(input("Enter second number: "))

result = DivExp(n1, n2)

if result is not None:

print("Result:", result)

................................................................................................................................................................
Output
Enter first number: 10
Enter second number: 5
Result: 2.0
................................................................................................................................................................
Output
Enter first number: -10
Enter second number: 5
AssertionError: Dividend must be positive.
................................................................................................................................................................
Output
Enter first number: 10
Enter second number: 0
Divide by zero error.
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.

CODE:
class Complex ():
def initComplex(self):
self.realPart = int(input("Enter the Real Part: "))
self.imgPart = int(input("Enter the Imaginary Part: "))
def display(self):
print(self.realPart,"+",self.imgPart,"i", sep="")
def sum(self, c1, c2):
self.realPart = c1.realPart + c2.realPart
self.imgPart = c1.imgPart + c2.imgPart

c1 = Complex()
c2 = Complex()
c3 = Complex()
print("Enter first complex number")
c1.initComplex()
print("First Complex Number: ", end="")
c1.display()
print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ", end="")
c2.display()
print("Sum of two complex numbers is ", end="")
c3.sum(c1,c2)
c3.display()

................................................................................................................................................................
OUTPUT:
Enter first complex number
Enter the Real Part: 4
Enter the Imaginary Part: 6
First Complex Number: 4+6i
Enter second complex number
Enter the Real Part: 4
Enter the Imaginary Part: 6
Second Complex Number: 4+6i
Sum of two complex numbers is 8+12i
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.

CODE:
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total = 0
def getMarks(self):
for i in range(3):
marks = int(input("Enter marks in subject " + str(i+1) + ": "))
self.marks.append(marks)
self.total += marks
def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:", self.marks)
print("Total:", self.total)
print("Percentage:", self.total / 3 * 100)

s1 = Student(input("Enter name: "), input("Enter USN: "))


s1.getMarks()
s1.display()
................................................................................................................................................................

OUTPUT:
Enter name: mki
Enter USN: 2sa1234
Enter marks in subject 1: 88
Enter marks in subject 2: 98
Enter marks in subject 3: 99
Name: mki
USN: 2sa1234
Marks: [88, 98, 99]
Total: 285
Percentage: 9500.0

You might also like