python programs

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

Python Lab Programs

1a.Develop a program to read the student details like USN, name and marks of three subjects .Display the
student details, total marks and percentage with suitable message

Program:

USN=input(" Enter Usn ")


name=input(" Enter Name:")
print(" Enter Marks Of 3 Subjects ")
marks=[] # define an Empty list marks
for i in range(3):
m=int(input(" Enter The Marks :"))
marks.append((m)) # load the values to list marks using append method
print(marks)
total=sum(marks) # calculate the total by using sum() function and store it in variable total
per=int(100*total)/300 # calculate the percentage and store it in variable per
print(USN,name,total,per)

Output:
Enter Usn 4BD22IS005
Enter Name: hafsa
Enter Marks Of 3 Subjects
Enter The Marks :90
[90]
Enter The Marks :60
[90, 60]
Enter The Marks :80
[90, 60, 80]
4BD22IS005 hafsa 230 76.66666666666667
1b.Develop a program to read the name and year of birth of a person .Display whether the person is senior
citizen or not.

Program:

import datetime

name=input('Enter your name')


birthyear=int(input('Enter the year'))
today= datetime.date.today() #used inbuilt function to read today‟s date (format yyyy-mm-dd)
print(today)
currentyear=today.strftime('%Y') # strftime (string format time)
print(currentyear)
age=int(currentyear)-int(birthyear)
print(age)
if age>=60:
print('you are a senior citizen')
else:
print('you are not a senior citizen')

Output:

Enter your name punith


Enter the year 2004
2023-01-11
2023
19
You are not a senior citizen

Enter your name sreenivas


Enter the year 1945
2023-01-11
2023
78
You are a senior citizen
2a. Develop a program to generate Fibonacci sequence of length(N).Read N from the console

Program:

def fib(n): # define a function Fibonacci


if n<=1:
return n
else:
return (fib(n-1)+fib(n-2)) # Recursion (recursive function can be defined that calls itself)

n=int(input('Enter n'))
if n<0:
print('Enter the positive number')
else:
print('fibonnaci sequence')
for i in range(n):
print(fib(i)) # Function call

Output:

Enter n 5
fibonnaci sequence
0
1
1
2
3
2b.Write a function to calculate a factorial of a number .Develop a program to compute binomial coefficient
(Given N and R)

def fact(n): # define a function Factorial(Fact)


if n==0:
return 1
else:
return n*fact(n-1) # Recursion (recursive function can be defined that calls itself)

n=int(input('Enter n'))
r=int(input('Enter r'))

if n<0 or r<0:
print('invalid')
else:
fn=fact(n) #Function call to calculate n!
Print(„Factorial of n is”,fn)
fr=fact(r) #Function call to calculate r!
Print(„Factorial of r is”,fr)
fnr=fact(n-r) #Function call to calculate (n-r)!
Print(„Factorial of n-r is”,fnr)
BC=fn/(fr*fnr) # computing binomial coefficient nCr= n!/r!*(n-r)!
print ('binomial coefficient is',BC)
------------------------------------------------------------------------------------------------------------------------------------------
Output:

Enter n 6
Enter r 3
Factorial of n is 720
Factorial of r is 6
Factorial of n-r is 6
Binomial coefficient is 20.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

def mean(data): # Function to find the mean


n = len(data)
mean = sum(data) / n
return mean

def variance(data): # Function to find the variance


n = len(data)
mean = sum(data) / n
deviations = [(x - mean) ** 2 for x in data]
variance = sum(deviations) / n
return variance

def stdev(data): # Function to find the Standard Deviation


var = variance(data)
std_dev = math.sqrt(var)
return std_dev

listA = [] # creating an empty list


n = int(input("Enter number of elements : ")) # number of elements as input

for i in range(0, n): # iterating till the range


element = int(input())
listA.append(element) # adding the element

print(listA) # Display the elements in the list

data=listA

print("Mean of the sample is % s " % (mean(data)))


print("variance of the sample is % s " % (variance(data)))
print("Standard Deviation of the sample is % s "% (stdev(data)))

----------------------------------------------------------------------------------------------------------------------------- --------------
Output:

Enter number of elements


10
4,8,6,5,3,2,8,9,2,5
[4,8,6,5,3,2,8,9,2,5]
Mean of the sample is 5.2
Variance of the sample is 5.76
Standard deviation of sample is 2.4
4. Read a multi-digit number (as chars) from the console. Develop a program to print frequency of each digit
with suitable example.

Program:

frequency={}
Print(“Enter the multi digit number”)
Digit=input()
For i in digit:
if i not in frequency :
frequency[i]=1
else:
frequency[i]=frequency[i]+1
print (frequency)

Output:

Enter the multi digit number


12345
{„1‟: 1,‟2‟: 1,‟3‟: 1, „4‟: 1, „5‟: 1}

Enter the multi digit number


12221333344
{„1‟: 2,‟2‟: 3,‟3‟: 4, „4‟: 2}
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]

Program:

file=open("D://Words.txt") # Provide the path of note pad file


text=file.read() # Read the file and store it in text
#print(text)
words=text.split() # split the text considering space between words
frequency={} # Create a dictionary frequency

for word in words:


if word not in frequency: # this part of the code will check whether the word is already
frequency[word]=1 # present in the dictionary if present it will execute else
else: # condition and increment frequency , if not present it will
frequency[word]+=1 # add word to the dictionary
#print(frequency)

most_frequent = dict(sorted(frequency.items(),key=lambda elem: elem[1],reverse=True)) # sort in descending order


#print(most_frequent)
out = dict(list(most_frequent.items())[0: 10]) # select the top 10 most frequently used words
print("1st 10 Most Frequent words are:"+str(out)) # print the output

--------------------------------------------------------------------------------------------------------------------------------------------

Prerequisites: Create a Text file (Words.txt) and add the Content


File name: Words.txt

Once upon a time there lived a poor widow and her son Jack. One day, Jack‟s mother told him to sell their only cow.
Jack went to the market and on the way he met a man who wanted to buy his cow

Output:

1st 10 Most Frequent words are :{'a': 3, 'to': 3, 'and': 2, 'Jack': 2, 'the': 2, 'Once': 1, 'upon': 1, 'time': 1, 'there': 1, 'lived'
: 1}
6. Develop a program to sort the contents of a text file and write the sorted contents into a separate text file

words = [ ]
f=open („D://sample.txt‟)
text= f.read()
content=text. split („\n‟)
for line in content:
temp=line. split ()
for w in temp:
words. append (w)
words. sort()
f1=open („D://new.txt‟, „w‟)
f1.write („ ‟.join (words))
f1.close ()
7. Develop a program to backing up a given folder (folder is a current working directory) into a ZIP file by using
relevant modules and suitable methods

from zipfile import ZipFile


import os

extension = input('Input file extension: ')

Zippy = ZipFile("Backup.zip", 'w')

for folder, subfolders, file in os.walk("C:\\Users"):


for subfolders in subfolders:
path = folder + subfolders
for x in file:
if x.endswith(extension):
filepath = folder + "\\" + x
print(filepath)
Zippy.write(filepath, compress_type=zipfile.ZIP_DEFLATED)
Zippy.close()

----------------------------------------------------------------------------------------------------------------------------- -
#! python3
# backupToZip.py
# Copies an entire folder and its contents into
# a zip file whose filename increments.

import zipfile, os

def backupToZip(folder):
# Backup the entire contents of "folder" into a zip file.
folder = os.path.abspath(folder) # make sure folder is absolute
# Figure out the filename this code should used based on
# what files already exist.
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1

# Create the zip file.


print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
# Add the current folder to the ZIP file.
backupZip.write(foldername)
# Add all the files in this folder to the ZIP file.
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\delicious')

You might also like