PRACTICAL FILE OF
PROGRAMMING WITH PYTHON
SUBMITTED BY- CHETNA RANI
ROLL NO – 24563/43
COURSE - BSC MATHEMATICS HONOURS
QUESTIONS:
QUES1. WAP to calculate total marks, percentage and grade of a student.
Marks obtained in each of three subjects are to be input by the user. Assign
grades according to the following criteria: Grade A: if Percentage >= 80 Grade
B: if Percentage >= 60 and Percentage < 80 Grade C: if Percentage >= 40 and
Percentage < 60 Grade D: if Percentage < 40
ANS.
print("enter the marks of five subjects:")
subject_1=float(input())
subject_2=float(input())
subject_3=float(input())
subject_4=float(input())
subject_5=float(input())
total=subject_1+subject_2+subject_3+subject_4+subject_5
average=total/5
percentage=(total/500)*100
if average>=90:
grade='A'
elif average>=80 and average<90:
grade='B'
elif average>=70 and average<80:
grade='C'
elif average >=60 and average<70:
grade='D'
else:
grade='E'
print("the total marks is:",total,"/500.00")
print("the average marks is:",average)
print("the percentage is :",percentage,"%")
print("the grade is :",grade)
OUTPUT:
QUES2. WAP to print factors of a given number
ANS.
def print_factors(x):
print("the factors of ", x ,"are:")
for i in range(1, x+1):
if x % i ==0:
print(i)
num = 320
print_factors(num)
QUES3. WAP to add N natural numbers and display their sum.
ANS.
C def sum_of_n_natural_numbers(num):
if(num==0):
return num
else:
return(num+sum_of_n_natural_numbers(num-1))
number= int(input("please enter any number:"))
total_value=sum_of_n_natural_numbers(number)
print("sum of natural numbers from 1 to {0}={1}".format(number,total_value))
QUES 4. WAP to print the following conversion table (use looping constructs)
ANS.
def print_conversion_table():
print("Height (in feet)\tHeight (in Inches)")
print("-" * 35)
Height_in_feet= 5.0
while Height_in_feet<=6.0:
Height_in_Inches = Height_in_feet*12
print(f"{Height_in_feet:.1f}ft\t\t{Height_in_Inches:.1f} Inches")
Height_in_feet+=0.1
print_conversion_table()
Ques 5:WAP that takes a positive integer n and the produce n lines of output as
shown:
*
**
***
* * * * (sample output for n = 4)
ANS.
print("Star Pattern Display")
num=1
x=num
for i in range(1,5,1):
num=num+1;
for j in range(1,num,1):
print('*', end=' ')
x=num+1
print()
Ques6: Write a menu driven program using user defined functions to print the area of rectangle,
square, circle and triangle by accepting suitable input from user.
ANS
import math
def area_rectangle():
length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
area = length * breadth
print(f"The area of the rectangle is: {area}")
def area_square():
side = float(input("Enter the side of the square: "))
area = side ** 2
print(f"The area of the square is: {area}")
def area_circle():
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"The area of the circle is: {area:.2f}")
def area_triangle():
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is: {area}")
def main():
while True:
print("\nMenu:")
print("1. Area of Rectangle")
print("2. Area of Square")
print("3. Area of Circle")
print("4. Area of Triangle")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
area_rectangle()
elif choice == '2':
area_square()
elif choice == '3':
area_circle()
elif choice == '4':
area_triangle()
elif choice == '5':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
if __name__ == "__main__":
main()
QUES 7 :Write a function that calculates factorial of a number n
ANS
def factorial_iterative(n):
if n < 0:
return "Factorial is not defined for negative numbers."
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
# Example usage:
number = int(input("Enter a number: "))
print(f"The factorial of {number} is: {factorial_iterative(number)}")
Ques 8:WAP to print the series and its sum: (use functions) 1/1! + 1/2! + 1/3!
…….1/n!
ANS. import math
def factorial(num):
"""Calculate the factorial of a number."""
return math.factorial(num)
def series_sum(n):
"""Calculate the series sum."""
total = 0
for i in range(1, n + 1):
total += 1 / factorial(i)
return total
def print_series_and_sum(n):
"""Print the series and its sum."""
series = " + ".join([f"1/{i}!" for i in range(1, n + 1)])
sum_of_series = series_sum(n)
print(f"The series is: {series}")
print(f"The sum of the series is: {sum_of_series:.5f}")
# Input from the user
n = int(input("Enter the value of n: "))
if n <= 0:
print("Please enter a positive integer.")
else:
print_series_and_sum(n)
Ques 9:WAP to perform the following operations on an input string
a. Print length of the string
ANS.
def print_string_length():
# Take input from the user
user_string = input("Enter a string: ")
# Calculate and print the length of the string
string_length = len(user_string)
print(f"The length of the string is: {string_length}")
# Call the function
print_string_length()
b. Find frequency of a character in the string
ANS.
def find_character_frequency():
# Take input from the user
user_string = input("Enter a string: ")
character = input("Enter the character to find its frequency: ")
# Ensure the character input is a single character
if len(character) != 1:
print("Please enter a single character.")
return
# Calculate the frequency of the character
frequency = user_string.count(character)
print(f"The frequency of '{character}' in the string is: {frequency}")
# Call the function
find_character_frequency()
c. Print whether characters are in uppercase or lowercase.
ANS def check_character_case():
# Take input from the user
user_string = input("Enter a string: ")
# Loop through each character in the string
for char in user_string:
if char.isupper():
print(f"'{char}' is uppercase.")
elif char.islower():
print(f"'{char}' is lowercase.")
else:
print(f"'{char}' is not a letter.")
# Call the function
check_character_case()
Ques 10: WAP to create two lists: one of even numbers and another of odd
numbers. The program should demonstrate the various operations and
methods on lists.
ANS
def create_even_odd_lists(numbers):
even_numbers = [num for num in numbers if num % 2 == 0]
odd_numbers = [num for num in numbers if num % 2 != 0]
return even_numbers, odd_numbers
def demonstrate_list_operations(even_list, odd_list):
print("\nEven Numbers List:", even_list)
print("Odd Numbers List:", odd_list)
# Append
even_list.append(100)
odd_list.append(101)
print("\nAfter appending 100 to Even List and 101 to Odd List:")
print("Even Numbers List:", even_list)
print("Odd Numbers List:", odd_list)
# Extend
even_list.extend([102, 104])
odd_list.extend([103, 105])
print("\nAfter extending Even List with [102, 104] and Odd List with [103,
105]:")
print("Even Numbers List:", even_list)
print("Odd Numbers List:", odd_list)
# Sort
even_list.sort()
odd_list.sort()
print("\nAfter sorting:")
print("Even Numbers List:", even_list)
print("Odd Numbers List:", odd_list)
# Index
print("\nIndex of 100 in Even List:", even_list.index(100))
print("Index of 101 in Odd List:", odd_list.index(101))
# Remove
even_list.remove(100)
odd_list.remove(101)
print("\nAfter removing 100 from Even List and 101 from Odd List:")
print("Even Numbers List:", even_list)
print("Odd Numbers List:", odd_list)
# Reverse
even_list.reverse()
odd_list.reverse()
print("\nAfter reversing the lists:")
print("Even Numbers List:", even_list)
print("Odd Numbers List:", odd_list)
# Main function
def main():
# Input numbers from the user
n = int(input("Enter the number of elements: "))
numbers = []
print("Enter the numbers:")
for _ in range(n):
numbers.append(int(input()))
even_list, odd_list = create_even_odd_lists(numbers)
demonstrate_list_operations(even_list, odd_list)
# Run the program
if __name__ == "__main__":
main()
Ques 11:WAP to create a dictionary where keys are numbers between 1
and 5 and the values are the cubes of the keys.
ANS
def create_cube_dictionary():
cube_dict = {key: key ** 3 for key in range(1, 6)}
return cube_dict
# Main function
def main():
cube_dict = create_cube_dictionary()
print("The dictionary with keys as numbers from 1 to 5 and values as their
cubes:")
print(cube_dict)
# Run the program
if __name__ == "__main__":
main()
QUES 12:WAP to create a tuple t1 = (1, 2, 5, 7, 2, 4). The program should
perform the following:
a. Print tuple in two lines, line 1 containing the first half of tuple and
second line having the second half.
def split_and_print_tuple():
t1 = (1, 2, 5, 7, 2, 4)
# Find the midpoint of the tuple
midpoint = len(t1) // 2
# Split the tuple into two halves
first_half = t1[:midpoint]
second_half = t1[midpoint:]
# Print the two halves
print("First half of the tuple:", first_half)
print("Second half of the tuple:", second_half)
# Run the function
split_and_print_tuple()
b. Concatenate tuple t2 = (10, 11) with t1.
ANS
def concatenate_tuples():
t1 = (1, 2, 5, 7, 2, 4)
t2 = (10, 11)
# Concatenate the tuples
concatenated_tuple = t1 + t2
# Print the concatenated tuple
print("Concatenated tuple:", concatenated_tuple)
# Run the function
concatenate_tuples()