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

Urhsndhrvanakwhzbxhdak

Uploaded by

ktvinyas00
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)
14 views10 pages

Urhsndhrvanakwhzbxhdak

Uploaded by

ktvinyas00
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

1.

A Basic Python program that reads student details, calculates the total marks, and
percentage, and then displays the results:
print("Enter the name of the Student")
name=input()
print("Enter the USN of the Student")
usn=input()
print("Enter the subject1 marks")
sub1=input()
print("Enter the subject2 marks")
sub2=input()
print("Enter the subject3 marks")
sub3=input()
total=int(sub1)+int(sub2)+int(sub3)
avg=int(total)/3.0
print("****************************************")
print("\t Student Details")
print("****************************************")
print("\t Student Name: ",name)
print("\t Student USN: ",usn)
print("\t Subject1 Marks: ",sub1)
print("\t Subject2 Marks: ",sub2)
print("\t Subject3 Marks: ",sub3)
print("*****************************************")
print("\t Total Marks: ",total)
print("Average of the marks: ",float(avg))
Alternate Program
# Read student details
name = input("Enter the student's name: ")
usn = input("Enter the student's USN: ")

# Read marks for three subjects


marks_1 = int(input("Enter the marks for the first subject: "))
marks_2 = int(input("Enter the marks for the second subject: "))
marks_3 = int(input("Enter the marks for the third subject: "))

# Calculate total marks and percentage


total_marks = marks_1 + marks_2 + marks_3
percentage = (total_marks / 300) * 100
# Assuming each subject is out of 100 marks

# Display student details, total marks, and percentage


print("\nStudent Details:")
print("-------------------")
print("Name:", name)
print("USN:", usn)
print("Marks in Subjects:")
print(f"Subject 1: {marks_1}")
print(f"Subject 2: {marks_2}")
print(f"Subject 3: {marks_3}")
print("-------------------")
print("Total Marks:", total_marks)
print(f"Percentage: {percentage:.2f}%")
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 of the Person")
name=input()
print("Enter the Year of birth of the person")
age=input()
senior=2022-int(age)
print("HI",name)
if (int(senior) >= 55):
print("you are senior citizen--Age: ",senior)
else:
print("you are not senior citizen---Age: ",senior)
Alternate Program
# Get the current year.
# Note: In practice, you might use the datetime module for this, but
to keep it simple, we'll manually set the current year.
#import datetime
## Get the current year using datetime
#current_year = datetime.datetime.now().year
current_year = 2023

# Read the person's name and year of birth


name = input("Enter the person's name: ")
year_of_birth = int(input("Enter the year of birth: "))

# Calculate age
age = current_year - year_of_birth

# Determine if the person is a senior citizen


if age >= 60:
print(f"{name} is a senior citizen.")
else:
print(f"{name} is not a senior citizen.")
2.A Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
# Prompt the user to enter a value for N
print("Enter the N value:")

# Read the user's input and store it in the variable 'n'


n = input()

# Initialize variables for Fibonacci sequence


a = 0
b = 1
i = 1

# Print a header for the Fibonacci series


print("The Fibonacci series")

# Print a separator
print("####################")

# Continue the loop as long as i is less than or equal to n


while int(i) <= int(n):
# Calculate the next Fibonacci number
c = int(a) + int(b)
# Print the current Fibonacci number
print("\t", c)
# Update 'a' and 'b' for the next iteration
a = b
b = c
# Increment the counter 'i'
i += 1

2.B Write a function to calculate factorial of a number. Develop a program to compute.


binomial coefficient (Given N and R).
# Prompt the user to enter the value of N
print("Enter N value")

# Read the user's input and store it in the variable 'n'


n = input()

# Prompt the user to enter the value of R


print("Enter R value")

# Read the user's input and store it in the variable 'r'


r = input()

# Define a factorial function


def fact(x):
x = int(x)
if (x == 1):
return 1
else:
return (x * fact(x - 1))
# Calculate the factorial of N and store it in 'factn'
factn = fact(n)

# Calculate the factorial of R and store it in 'factr'


factr = fact(r)

# Calculate N - R and store it in 'm'


m = int(n) - int(r)

# Calculate the factorial of (N - R) and store it in 'factm'


factm = fact(m)

# Calculate the binomial coefficient


bio = factn / (factr * factm)

# Print the factorial of R


print("R factorial is:", factr)

# Print the factorial of N


print("N factorial is:", factn)

# Print the Binomial Coefficient series


print("The Binomial Coefficient series is:", bio)
3 Read N numbers from the console and create a list. Develop a program to print
mean, variance and standard deviation with suitable messages.
# Define a function to calculate the mean of a list of numbers
def calculate_mean(numbers):
return sum(numbers) / len(numbers)

# Define a function to calculate the variance of a list of


numbers given the mean
def calculate_variance(numbers, mean):
return sum((x - mean) ** 2 for x in numbers) / len(numbers)

# Define a function to calculate the standard deviation given


the variance
def calculate_std_dev(variance):
return variance ** 0.5

# Prompt the user to input the number of values


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

# Initialize an empty list to store the numbers


numbers = []

# Loop to get N numbers from the user


for i in range(n):
num = float(input(f"Enter number {i+1}: "))
numbers.append(num)

# Calculate the mean of the entered numbers


mean = calculate_mean(numbers)

# Calculate the variance using the mean


variance = calculate_variance(numbers, mean)

# Calculate the standard deviation using the variance


std_dev = calculate_std_dev(variance)

# Print the calculated statistics


print(f"\nMean: {mean}")
print(f"Variance: {variance}")
print(f"Standard Deviation: {std_dev}")

Alternate Program
import numpy as np

# Prompt the user to input the number of values


print("How many numbers are there: ")
n = int(input())

# Initialize an empty list to store the numbers


lst = []

# Prompt the user to enter N elements and add them to the list
print(f"Enter {n} elements to the list. \"Enter them one by
one.\"")
for i in range(n):
ele = input()
lst.append(int(ele))

# Print the list of numbers


print("List of numbers:", lst)

# Calculate and print the mean


mean = np.average(lst)
print("The mean of N elements is:", mean)

# Calculate and print the variance


var = np.var(lst)
print("The variance of the N elements is:", var)

# Calculate and print the standard deviation


stan = np.std(lst)
print("The standard deviation of N elements is:", stan)

4 Read a multi-digit number (as chars) from the console. Develop a program to print
the frequency of each digit with suitable message.
print("Enter a mutidigit number:")
num=input()
dict={}
for x in num:
if x in dict:
dict[x]+=1
else:
dict[x]=1
print(str(dict))

5 Develop a program to print 10 most frequently appearing words in a text file. [Hint:
Use dictionary
import operator # Import the 'operator' module

# Prompt the user to enter a file name


print("Enter the file name")
fname = input() # Read the user's input as the file name
fp = open(fname, 'r') # Open the file for reading
list = {} # Initialize an empty dictionary to store word frequencies

# Loop through each line in the file


for line in fp:
# Split the line into words
for word in line.split():
# Check if the word is already in the dictionary
if word in list:
list[word] += 1
else:
list[word] = 1

# Print all word occurrences before sorting


print("ALL words occurrence before sorting")
print(str(list))

# Sort the dictionary by word frequency in descending order and take


the top 10
sorted_list = dict(sorted(list.items(), key=operator.itemgetter(1),
reverse=True)[:10])

# Print the top 10 words and their frequencies


print("Sorted list of 10 words occurrence from higher to lower")
print(str(sorted_list))

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()].
# Prompt the user to enter a file name
print("Enter the file name:")
fname = input()

# Open the specified file in read mode


fp = open(fname, 'r')

# Read all lines from the file


lines = fp.readlines()

# Initialize an empty list to store words


words = []

# Loop through each line in the file


for line in lines:
# Split the line into words add to list and iterate over them
for word in line.split():
word.strip(" ")
words.append(word)

# Sort the list of words


words.sort()

# Print the sorted list


print("Sorted list")
print(words)

# Open a new file for writing the sorted words


fo = open("program6out.txt", 'w')

# Write each word to the file, followed by a newline


for item in words:
fo.write(item + "\n")

# Close the output file


fo.close()

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 shutil
import os.path

# Creating the ZIP file


archived = shutil.make_archive('backup-folder', 'zip', 'backup-
folder')

if os.path.exists('backup-folder.zip'):
print("The path the folder is zipped:::")
print(archived)
else:
print("ZIP file not created")

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.
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
def DivExp(x, y):
try:
z=x/y
print("Quotient:",z)
except ZeroDivisionError:
print("Division by Zero!")
DivExp(a, b)

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

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 StudentData:
def __init__(self):
self.Total = 0.00
self.Average = 0.00
self.Percentage = 0.00
self.Marks = []
self.MaxMarks = 0.00

def main(self):
print("Enter the marks of five subjects::")

for i in range(5):
self.Marks.append( float (input ()))

def CalcMaxMarks (self):


return len (self.Marks) * 100

def CalcTotal (self):


self.Total = 0
for i in self.Marks:
self.Total += i
return self.Total

def CalcAvg (self):


self.Average = self.Total / len (self.Marks)
return self.Average

def CalcPercentage (self):


return (self.Total * 100) / (len (self.Marks) * 100)

def CalcGrade (self):


Grade = None
if self.Average >= 90:
Grade = 'A'
elif self.Average >= 80 and self.Average < 90:
Grade = 'B'
elif self.Average >= 70 and self.Average < 80:
Grade = 'C'
elif self.Average >= 60 and self.Average < 70:
Grade = 'D'
else:
Grade = 'E'
return Grade

def CalcResult (self):


c = 0
for i in self.Marks:
if i >= 40:
c += 1

if c == len (self.Marks):
return 'Passed'
else:
return 'Failed'

# It will create instance of the StudentData class


StudentData = StudentData()

StudentData.main()

# It will produce the final output


print ("\nThe Total marks is: \t", StudentData.CalcTotal(),
"/", StudentData.CalcMaxMarks())
print ("\nThe Average marks is: \t", StudentData.CalcAvg())
print ("\nThe Percentage is: \t",
StudentData.CalcPercentage(), "%")
print ("\nThe Grade is: \t", StudentData.CalcGrade())

You might also like