0% found this document useful (0 votes)
15 views5 pages

Python Programs for Student Data and Calculations

The document outlines a series of programming tasks, including reading student details, generating Fibonacci sequences, calculating factorials, and determining senior citizen status based on age. It also covers statistical calculations like mean, variance, and standard deviation, as well as text processing tasks such as counting word frequency and sorting file contents. Additionally, it includes error handling for division operations and backing up folders into ZIP files.

Uploaded by

WOLFIE
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)
15 views5 pages

Python Programs for Student Data and Calculations

The document outlines a series of programming tasks, including reading student details, generating Fibonacci sequences, calculating factorials, and determining senior citizen status based on age. It also covers statistical calculations like mean, variance, and standard deviation, as well as text processing tasks such as counting word frequency and sorting file contents. Additionally, it includes error handling for division operations and backing up folders into ZIP files.

Uploaded by

WOLFIE
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

1. a. Develop a program to read the student details like Name, USN, and 2. a.

a. Develop a program to generate Fibonacci sequence of length (N). Read N


Marks in three subjects. Display the student details, total marks and from the console.
percentage with suitable messages.
def fib (n):
name = input ('Enter name of the student:') a=0
USN = input ('Enter the USN of the student:') b =1
m1 = int (input ('Enter the marks in the first subject:')) if n == 1:
m2 = int (input ('Enter the marks in the second subject:')) print (a)
m3 = int (input ('Enter the marks in the third subject:')) else:
print(a)
total_marks = m1 + m2 + m3 print(b)
percentage = (total_marks/300) *100
for i in range (2,n):
c=a+b
print ('Student details are:')
a=b
print ('Name is:', name)
b=c
print ('USN is:', USN) print (c)
print ('Marks in the first subject:', m1) fib(5)
print ('Marks in the second subject:', m2)
print ('Marks in the third subject:', m3)
print ('Total Marks obtained:', total_marks) 2. b. Write a function to calculate factorial of a number. Develop a program to
print ('Percentage of marks:', percentage) compute binomialcoefficient (Given N and R).

def fact(num):
1. b. Develop a program to read the name and year of birth of a person.
Display whether the person is asenior citizen or not. if num == 0:
return 1
name = input ('Enter the name of a person:')
year_of_birth = int (input ('Enter the birth year:')) else:
age = 2023-year_of_birth return num * fact(num-1)

print ('The age is:', age) n = int(input("Enter the value of N : "))


if age>60:
r = int(input("Enter the value of R (R cannot be negative or greater than N): "))
print ('The person is senior citizen')
else: nCr = fact(n)/(fact(r)*fact(n-r))
print ('The person is not senior citizen')
print(n,'C',r," = ","%d"%nCr,sep=" ")
3. Read N numbers from the console and create a list. Develop a program to 4. Read a multi-digit number (as chars) from the console. Develop a program
print mean, variance andstandard deviation with suitable messages. to print the frequency of each digit with suitable message.

num = input("Enter a number : ")


from math import sqrt
print("The number entered is :", num)
myList = []
freq = set(num)
num = int(input("Enter the number of elements in your list : "))
for digit in freq:
for i in range(num):
val = int(input("Enter the element : ")) print(digit, "occurs", [Link](digit), "times")

[Link](val)
print('The length of list is', len(myList))
print('List Contents', myList)
# Mean Calculation
total = 0
for elem in myList:
total += elem
mean = total / num
# Variance Calculation
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
variance = total / num
# Standard Deviation Calculation
stdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", stdDev)
5. Develop a program to print 10 most frequently appearing words in a text text = open("[Link]", "r")
file. [Hint: Use dictionary with distinct words and their frequency of d = dict()
occurrences. Sort the dictionary in the reverse order of frequency and display for line in text:
dictionary slice of first 10 items] line = [Link]()
line = [Link]()
# Open the file in read mode words = [Link](" ")
text = open("[Link]", "r") for word in words:
# Create an empty dictionary if word in d:
d = dict() d[word] = d[word] + 1
# Loop through each line of the file else:
d[word] = 1
for line in text:
for key in list([Link]()):
# Remove the leading spaces and newline character print(key, ":", d[key])
line = [Link]()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = [Link]()
# Split the line into words
words = [Link](" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list([Link]()):
print(key, ":", d[key])
6. Develop a program to sort the contents of a text file and write the sorted 7. Develop a program to backing Up a given Folder (Folder in a current
contents into a separate text file. [Hint: Use string methods strip(), len(), list working directory) into a ZIP File by using relevant modules and suitable
methods sort(), append(), and file methods open(), readlines(), and write()]. methods.

import [Link]
import sys
import os
fname = input("Enter the filename whose contents are to be sorted : ")#sample file import sys
[Link] also provided import pathlib
import zipfile
infile = open(fname, "r")
dirName = input("Enter Directory name that you want to backup : ")
myList = [Link]()
# print(myList) curDirectory = [Link](dirName)
#Remove trailing \n characters with [Link]("[Link]", mode="w") as archive:
lineList = [] for file_path in [Link]("*"):
for line in myList: [Link](file_path, arcname=file_path.relative_to(curDirectory))
[Link]([Link]()) if [Link]("[Link]"):
print("Archive", "[Link]", "created successfully")
[Link]() else:
#Write sorted contents to new file [Link] print("Error in creating zip archive")

outfile = open("[Link]","w")

for line in lineList:


[Link](line + "\n")

[Link]() # Close the input file


[Link]() # Close the output file

if [Link]("[Link]"):
print("[Link] contains", len(lineList), "lines")
print("Contents of [Link]")
rdFile = open("[Link]","r")
for line in rdFile:
print(line, end="")
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

import sys

def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
[Link](0)
else:
return c
val1 = int(input("Enter a value for a : "))
val2 = int(input("Enter a value for b : "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)

Common questions

Powered by AI

To determine the frequency of digits in a multi-digit number in Python, you can convert the number to a string to iterate over each character, then use a set to identify unique digits. For each digit, count the occurrences using the string `count()` method, which tallies how many times a specific character appears within the string .

Use assertions to ensure preconditions, such as `a > 0`, are met. To handle division, use `try` and `except` blocks to catch `ZeroDivisionError` if `b` is zero, printing an error message and exiting the program safely. The use of assertions and exceptions ensures robust input validation and error reporting .

First, open the input file in read mode to access its lines, which are read into a list after stripping newline characters. Sort this list and then open a new output file in write mode, where the sorted lines are written back. Finally, close both files and confirm the new file's existence to ensure that sorting was successful .

Read the student's name, USN, and marks in three subjects through input prompts. Calculate the total marks by summing the marks of the three subjects. The percentage is computed by dividing the total marks by the maximum possible marks (300), then multiplying by 100. Display the student details along with calculated total marks and percentage .

A person is classified as a senior citizen if their age is greater than 60. You can calculate the age by subtracting the year of birth from the current year, 2023. If the calculated age exceeds 60, the person is considered a senior citizen; otherwise, they are not .

To generate the Fibonacci sequence up to a specified length, N, initialize the first two numbers and iterate to compute subsequent numbers by summing the last two. If N equals 1, only the first number is printed. For larger N, a loop runs starting from 2 up to N-1, adding and updating the last two values until the sequence is complete .

Calculating the binomial coefficient N choose R involves using the factorial function. Programmatically, this is implemented by defining a recursive function `fact()` to compute the factorial of N, R, and N-R. Then, the binomial coefficient is given as `nCr = fact(n)/(fact(r)*fact(n-r))`. This uses the mathematical formula for combinations, which is `N! / (R!(N-R)!)` .

To calculate the mean, sum all elements in the list and divide by the number of elements. For variance, sum the squared differences between each element and the mean, then divide by the number of elements. The standard deviation is the square root of the variance. These calculations are all done programmatically using loops to iterate through the user-inputted list values .

To back up a folder into a ZIP file, use the `os`, `pathlib`, and `zipfile` modules. Begin by specifying the folder to compress. `pathlib.Path` is used to navigate and list all files within the directory, while `zipfile.ZipFile` creates the archive. Each file is added to the archive with its path relative to the folder being zipped. These operations confirm the archive's creation .

Use a dictionary to map words to their frequency. Open the text file, iterate line by line, and split each line into words after stripping spaces and converting to lowercase to avoid case mismatch. For each word, update the frequency count in the dictionary. Sort the dictionary by frequency in descending order and select the top 10 words to understand their distribution in the text file .

You might also like