0% found this document useful (0 votes)
12 views10 pages

First Two PLC Lab Programs Eee - Ec

The document contains a series of Python programming lab exercises that cover various topics such as reading student details, calculating Fibonacci sequences, computing factorials and binomial coefficients, statistical analysis of lists, digit frequency in numbers, word frequency in text files, sorting file contents, and backing up folders into ZIP files. Each exercise includes code snippets and expected output examples. The document serves as a practical guide for beginners to learn Python programming through hands-on tasks.

Uploaded by

Shahina
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)
12 views10 pages

First Two PLC Lab Programs Eee - Ec

The document contains a series of Python programming lab exercises that cover various topics such as reading student details, calculating Fibonacci sequences, computing factorials and binomial coefficients, statistical analysis of lists, digit frequency in numbers, word frequency in text files, sorting file contents, and backing up folders into ZIP files. Each exercise includes code snippets and expected output examples. The document serves as a practical guide for beginners to learn Python programming through hands-on tasks.

Uploaded by

Shahina
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/ 10

INTRODUCTION TO PYTHON PROGRAMMING

 LAB PROGRAMS

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

name = input("Enter student's name: ")


usn = input("Enter student's USN: ")
marks1 = int(input("Enter marks obtained in subject 1: "))
marks2 = int(input("Enter marks obtained in subject 2: "))
marks3 = int(input("Enter marks obtained in subject 3: "))
totalmarks = marks1 + marks2 + marks3
percentage = (totalmarks / 300)* 100
print("Student Details:")
print("Name:", name)
print("USN:", usn)
print("Total Marks:", totalmarks)
print("Percentage:", percentage)

➢ Output
# 1b. Develop a program to read the name and year of birth of a
person. Display whether the person is a senior citizen or not.

name = input("Enter your name: ")


yearofbirth = int(input("Enter your year of birth: "))
currentyear = 2023
age = currentyear – yearofbirth
if age >= 60:
print(name, "is a senior citizen.")
else:
print(name, "is not a senior citizen.")

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

def generate_fibonacci_sequence(length):
sequence = [0, 1]
for i in range(2, length):
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)
return sequence

def main():
try:
N = int(input("Enter the length of the Fibonacci sequence: "))
if N <= 0:
print("Length should be a positive integer.")
else:
fibonacci_sequence = generate_fibonacci_sequence(N)
print("Fibonacci sequence of length", N, ":", fibonacci_sequence)
except ValueError:
print("Please enter a valid integer for length.")

if __name__ == "__main__":
main()

➢ Output:

Enter the length of Fibonacci Series


5
Fibonacci Series for the length 5 is as follows
0
1
1
2
3
# 2b. Write a function to calculate factorial of a number. Develop a program to
compute binomial coefficient (Given N and R).

def fact(num):
fact = 1
for i in range(num, 0, -1):
fact = fact * i
return factN = int(input("Enter the value for N: ")
R = int(input("Enter the value for R: "))
NF = fact(N)
RF = fact(R)
print("Factorial of " + str(N) + " is", NF)
BMC = NF / (RF * NRF)
print("Binomial coefficient is", BMC)

➢ Output:

Enter the value for N


4
Enter the value for R
2
Factorial of 4 is 24
Binomial co efficient is 6

# 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
n = int(input('Enter the number of elements:'))
lst = []
for i in range(n):
num = float(input('Enter number ' + str(i + 1) + ':'))
lst.append(num)
mean = sum(lst) / n
k = 0
for x in lst:
k = k + ((x - mean) ** 2)
variance = k / n
std_dev = math.sqrt(variance)
print('The list is', lst)
print('The mean of the list is:', mean)
print('The variance of the list is:', variance)
print('The standard Deviation of the list is:', std_dev)
➢ Output:

Enter the number of elements:4


Enter number1:1
Enter number2:2
Enter number3:3
Enter number4:4
The list is [1.0, 2.0, 3.0, 4.0]
The mean of the list is: 2.5
The variance of the list is: 1.25
The standard Deviation of the list
is: 1.11803398

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

number = input("Enter a multi-digit number: ")


count = {}
for character in number:
count.setdefault(character,0)
count[character] = count[character] + 1
print('Digit Frequency:',count)

➢ Output:

Enter a multi-digit number:


22131244688553321
Digit Frequency: {'2': 4, '1': 3,
'3': 3, '4': 2, '61, '8': 2, '5': 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

import sys
import string
import os.path

fname = input("Enter the filename : ") #sample file text.txt also provided

if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
filecontents = ""
for line in infile:
for ch in line:
if ch not in string.punctuation:
filecontents = filecontents + ch
else:
filecontents = filecontents + ' '

wordFreq = {}
wordList = filecontents.split()
#Calculate word Frequency
for word in wordList:
if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1

sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )


#Display 10 most frequently appearing words with their count
print("\n===================================================")
print("10 most frequently appearing words with their count")
print("===================================================")
for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1], "times")

➢ Output:
# 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()].

import os.path
import os.sys
fname = input("Enter the filename whose contents are to be sorted : ")
#sample file unsorted.txt also provided
if not os.path.isfile(fname):
print("File", fname, "doesn't
exists") sys.exit(0)

infile = open(fname, "r")

myList =
infile.readlines()
# print(myList)

#Remove trailing \n
characters lineList = []
for line in myList:
lineList.append(line.str
ip())

lineList.sort()

#Write sorted contents to new file sorted.txt

outfile =
open("sorted.txt","w")

for line in lineList:


outfile.write(line + "\n")

infile.close() # Close the input file


outfile.close() # Close the output file

if os.path.isfile("sorted.txt"): print("\nFile containing


sorted content sorted.txt created successfully")
print("sorted.txt contains", len(lineList), "lines")
print("Contents of sorted.txt")
print("=================================================================")
rdFile =
open("sorted.txt","r")
for line in rdFile:
print(line, end="")

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

#
7.
# #
# #
# #
#
8.
# 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,p):
assert a>0, “the a is less than 0”
if b==0:
raise Exception('b should not be equal to 0')
c=a/b
return c
try:
print("enter the a value")
a=int(input())
print ('enter the b values')
b=int(input())
print(DivExp(a,b))
except Exception as err:
print(err

You might also like