0% found this document useful (0 votes)
24 views

Python Practical Exam Question Bank Solution

The document contains a question bank of Python practical exam solutions covering various topics such as area calculation, unit conversion, simple interest calculation, basic arithmetic operations, task management, student enrollment management, and more. Each section provides a brief description of the task, followed by the corresponding Python code to implement the solution. The document serves as a comprehensive guide for students to practice and understand Python programming concepts.

Uploaded by

stdsx146nissimt
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)
24 views

Python Practical Exam Question Bank Solution

The document contains a question bank of Python practical exam solutions covering various topics such as area calculation, unit conversion, simple interest calculation, basic arithmetic operations, task management, student enrollment management, and more. Each section provides a brief description of the task, followed by the corresponding Python code to implement the solution. The document serves as a comprehensive guide for students to practice and understand Python programming concepts.

Uploaded by

stdsx146nissimt
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/ 19

Python Practical Exam Question Bank Solution

1. Area Calculator
Input: shape type (circle, rectangle, triangle)
Output: Area using appropriate formula

import math
print("Choose a geometric figure to calculate the area:")
print("1. Circle")
print("2. Rectangle")
print("3. Triangle")
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"The area of the circle is: {area:.2f}")
elif choice == 2:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"The area of the rectangle is: {area:.2f}")
elif choice == 3:
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:.2f}")
else:
print("Invalid choice!")

2. Unit Converter
Example: Rupees ↔ Dollar, Celsius ↔ Fahrenheit, Inches ↔ Feet

print("Choose a conversion utility:")


print("1. Rupees to Dollar")
print("2. Temperature (Celsius to Fahrenheit)")
print("3. Inch to Feet")
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
rupees = float(input("Enter amount in Rupees: "))
exchange_rate = float(input("Enter exchange rate (1 Rupee = ? Dollar): "))
dollars = rupees * exchange_rate
print(f"{rupees} Rupees = {dollars:.2f} Dollars")
elif choice == 2:
celsius = float(input("Enter temperature in Celsius: "))

fahrenheit = (celsius * 9/5) + 32


print(f"{celsius}°C = {fahrenheit:.2f}°F")
elif choice == 3:
inches = float(input("Enter length in Inches: "))
feet = inches / 12
print(f"{inches} Inches = {feet:.2f} Feet")
else:
print("Invalid choice!")

3. Simple Interest Calculator


Formula: SI = P × R × T / 100

principal = float(input("Enter the principal amount: "))


rate = float(input("Enter the rate of interest (in %): "))
time = float(input("Enter the time period (in years): "))
simple_interest = (principal * rate * time) / 100
print(f"The Simple Interest is: {simple_interest:.2f}")

4. Basic Arithmetic Operations


Input: two numbers
Output: add, subtract, multiply, divide, modulus

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2
print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division:.2f}")
print(f"Modulus: {modulus}")
5. Task List Manager
Add, remove, update tasks using lists and tuples

tasks = []
while True:
print("\nTask List Manager")
print("1. Add a task")
print("2. Remove a task")
print("3. Update a task")
print("4. View tasks")
print("5. Sort tasks")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
task = input("Enter the task to add: ")
tasks.append(task)
print("Task added!")
elif choice == 2:
task = input("Enter the task to remove: ")
if task in tasks:
tasks.remove(task)
print("Task removed!")
else:
print("Task not found!")
elif choice == 3:
old_task = input("Enter the task to update: ")
if old_task in tasks:
new_task = input("Enter the new task: ")
index = tasks.index(old_task)
tasks[index] = new_task
print("Task updated!")
else:
print("Task not found!")
elif choice == 4:
print("Current Tasks:")
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
elif choice == 5:
tasks.sort()
print("Tasks sorted!")
elif choice == 6:
print("Exiting Task List Manager.")
break
else:
print("Invalid choice! Please try again.")
6. Student Enrollment Set Operations
Input: students in JEE/CET/NEET
Output: Union, intersection, difference using sets

cet_students = {"Alice", "Bob", "Charlie"}


jee_students = {"Bob", "David", "Eve"}
neet_students = {"Alice", "Eve", "Frank"}
while True:
print("\nStudent Enrollment Manager")
print("1. View all students in CET, JEE, or NEET")
print("2. Union (students enrolled in any exam)")
print("3. Intersection (students enrolled in all exams)")
print("4. Difference (students enrolled in CET but not JEE)")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print("CET Students:", cet_students)
print("JEE Students:", jee_students)
print("NEET Students:", neet_students)
elif choice == 2:
all_students = cet_students.union(jee_students).union(neet_students)
print("Students enrolled in any exam:", all_students)
elif choice == 3:
common_students =
cet_students.intersection(jee_students).intersection(neet_students)
print("Students enrolled in all exams:", common_students)
elif choice == 4:
cet_not_jee = cet_students.difference(jee_students)
print("Students enrolled in CET but not JEE:", cet_not_jee)
elif choice == 5:
print("Exiting Student Enrollment Manager.")
break
else:
print("Invalid choice! Please try again.")

7. Student Record Dictionary


Store name, grade, attendance; update and retrieve

students = {}
while True:
print("\nStudent Record Keeper")

print("1. Add a student record")


print("2. Update a student record")
print("3. View all student records")
print("4. Delete a student record")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:

name = input("Enter the student’s name: ")


grades = input("Enter the student’s grades (comma-separated):
").split(",")
attendance = int(input("Enter the student’s attendance (%): "))
students[name] = {"Grades": grades, "Attendance": attendance}
print("Student record added!")
elif choice == 2:
name = input("Enter the student’s name to update: ")
if name in students:
grades = input("Enter the updated grades (comma-separated):
").split(",")
attendance = int(input("Enter the updated attendance (%): "))
students[name] = {"Grades": grades, "Attendance": attendance}
print("Student record updated!")
else:
print("Student not found!")
elif choice == 3:
print("Student Records:")
for name, record in students.items():
print(f"Name: {name}, Grades: {', '.join(record['Grades'])},
Attendance: {record['Attendance']}%")
elif choice == 4:
name = input("Enter the student’s name to delete: ")
if name in students:
del students[name]
print("Student record deleted!")
else:
print("Student not found!")
elif choice == 5:
print("Exiting Student Record Keeper.")
break
else:
print("Invalid choice! Please try again.")

8. Pattern Printer
Print triangle/star patterns using loops
def triangle_pattern(n):
for i in range(1, n + 1):
print("*" * i)

rows = int(input("Enter the number of rows for the triangle: "))


triangle_pattern(rows)

9. Character Type Checker


Check if a given input is digit, lowercase, uppercase, special character

char = input("Enter a single character: ")


if char.isdigit():
print(f"’{char}’ is a digit.")
elif char.islower():
print(f"’{char}’ is a lowercase character.")
elif char.isupper():
print(f"’{char}’ is an uppercase character.")
else:
print(f"’{char}’ is a special character.")

10. Fibonacci Generator (Using Loop)


Generate first n numbers in the Fibonacci series

n = int(input("Enter the number of terms in the Fibonacci sequence: "))


t1, t2, t3 = 0, 1, 0
print("Fibonacci Sequence:")
while n > 0:
print(t3, end=" ")
t1 = t2
t2 = t3
t3 = t1 + t2
n -= 1

11. Factorial Calculator


Use function to calculate factorial of n

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

num = int(input("Enter a number to calculate its factorial: "))


if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}.")

12. Prime Checker


Function that returns whether a number is prime

def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

number = int(input("Enter a number to check if it is prime: "))


if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

13. Extract Words from File


Read file and extract words of length 3, 4, 5 etc.

def extract_words(file_path, length):


with open(file_path, 'r') as file:
words = file.read().split()
selected_words = [word for word in words if len(word) == length]
print(f"Words of length {length}: {selected_words}")

# Example Usage
extract_words("sample.txt", 4) # Change "sample.txt" to your filename
14. Sort City Names from File
Read city names, sort them alphabetically, write to a new file

def sort_cities(input_file, output_file):


with open(input_file, 'r') as file:
cities = file.readlines()

sorted_cities = sorted(city.strip() for city in cities)

with open(output_file, 'w') as file:


for city in sorted_cities:
file.write(city + "\n")

# Example Usage
sort_cities("cities.txt", "sorted_cities.txt")

15. Safe Division Calculator


Take two numbers and handle division by zero with try-except

def divide_numbers():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")

# Example Usage
divide_numbers()

16. Swap and Check Number Sign


Write a python program to swap two numbers and check if the first number is
positive, negative or zero.

def swap_numbers(a, b):


return b, a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

num1, num2 = swap_numbers(num1, num2)


print(f"After swapping: First number = {num1}, Second number = {num2}")

if num1 > 0:
print("The first number is positive.")
elif num1 < 0:
print("The first number is negative.")
else:
print("The first number is zero.")

17. Numbers Divisible by 4


Write a python program to print all the numbers divisible by 4 in the range 1 to n (use
for loop)

def print_divisible_by_4(n):
for i in range(1, n + 1):
if i % 4 == 0:
print(i)

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


print_divisible_by_4(n)

18. Factorial Using While Loop


Write a python program to find the factorial of an input number (use while loop).

# Program to find the factorial of an input number using a while loop

def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
result = 1
while n > 0:
result *= n
n -= 1
return result
# Input from the user
try:
num = int(input("Enter a number to find its factorial: "))
print(f"The factorial of {num} is {factorial(num)}")
except ValueError:
print("Please enter a valid integer.")

19. Simple Calculator - Menu Driven


Write a menu-driven python program to build simple calculator functions.

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0:
return a / b
else:
return "Error! Division by zero."

def calculator():
while True:
print("\nSimple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '5':
print("Exiting the calculator. Goodbye!")
break

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

if choice == '1':
print(f"The result is: {add(num1, num2)}")
elif choice == '2':
print(f"The result is: {subtract(num1, num2)}")
elif choice == '3':
print(f"The result is: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
calculator()

20. Fibonacci Series - Loop Based


Write a python program to display Fibonacci series of n number.

n = int(input("Enter the number of terms in the Fibonacci sequence: "))


t1, t2, t3 = 0, 1, 0
print("Fibonacci Sequence:")
while n > 0:
print(t3, end=" ")
t1 = t2
t2 = t3
t3 = t1 + t2
n -= 1

21. Array Operations


Write a python program to perform following operations on an array:

o Sum of all even elements

o Count the number of elements divisible by 3

o Insert 2 elements at the end of the list

o Delete all the odd elements from the list


def array_operations(arr):
# Sum of all even elements
sum_even = sum(x for x in arr if x % 2 == 0)

# Count of elements divisible by 3


count_div_by_3 = sum(1 for x in arr if x % 3 == 0)

# Insert 2 elements at the end of the list


arr.extend([int(input("Enter first element to insert: ")), int(input("Enter
second element to insert: "))])

# Delete all odd elements from the list


arr = [x for x in arr if x % 2 == 0]

return sum_even, count_div_by_3, arr

# Input from the user


n = int(input("Enter the number of elements in the array: "))
arr = []
for _ in range(n):
arr.append(int(input("Enter element: ")))

sum_even, count_div_by_3, updated_arr = array_operations(arr)


print("Sum of all even elements:", sum_even)
print("Count of elements divisible by 3:", count_div_by_3)
print("Updated array after operations:", updated_arr)

22. Multiline String Analysis


Write a python program to input a multiline string or a paragraph & count the
number of words & characters in the string.

# Program to count the number of words and characters in a multiline string or


paragraph

def count_words_and_characters():
# Input a multiline string from the user
print("Enter a multiline string (press Enter twice to end):")
lines = []
while True:
line = input()
if line == "":
break
lines.append(line)
paragraph = "\n".join(lines)

# Count words and characters


word_count = len(paragraph.split())
char_count = len(paragraph)

print(f"Number of words: {word_count}")


print(f"Number of characters: {char_count}")

if __name__ == "__main__":
count_words_and_characters()

23. Recursive Sum of Digits


Write a recursive function in python to find the Sum of the digits of the numbers.

def sum_of_digits(n):
# Base case: if the number is a single digit, return it
if n < 10:
return n
# Recursive case: add the last digit to the sum of the digits of the rest of
the number
return n % 10 + sum_of_digits(n // 10)

# Example usage
if __name__ == "__main__":
number = int(input("Enter a number: "))
print(f"The sum of the digits of {number} is {sum_of_digits(number)}")

24. Student Marks with Tuples - Menu Driven


Write a menu-driven python program to:

o Add students’ marks information in terms of tuples

o Calculate the total and average marks

o Display students with specified key

def add_student_marks():
students = []
while True:
name = input("Enter student name (or type 'done' to finish): ")
if name.lower() == 'done':
break
marks = tuple(
map(int, input("Enter marks separated by spaces: ").split()))
total = sum(marks)
average = total / len(marks)
students.append((name, marks, total, average))
return students

def display_student_by_key(students, key):


for student in students:
if student[0] == key:
print(
f"Name: {student[0]}, Marks: {student[1]}, Total: {student[2]},
Average: {student[3]:.2f}")
return
print("Student not found.")

def main():
students = []
while True:
print("\nMenu:")
print("1. Add students' marks information")
print("2. Display student by name")
print("3. Exit")
choice = input("Enter your choice: ")

if choice == '1':
students = add_student_marks()
elif choice == '2':
key = input("Enter the name of the student to search: ")
display_student_by_key(students, key)
elif choice == '3':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()
25. Set Operations
Write a menu-driven program to demonstrate the use of set in python:

o Accept two strings from the user

o Display common letters in two input strings (set intersection)

o Display letters which are in the first string but not in the second string (set
difference)

o Display set of all letters from both the strings (set union)

o Display set of letters which are in two strings but not common (Symmetric
Difference)

def accept_strings():
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
return str1, str2

def display_common_letters(str1, str2):


common = set(str1) & set(str2)
print(f"Common letters: {', '.join(common)}")

def display_difference_letters(str1, str2):


difference = set(str1) - set(str2)
print(
f"Letters in the first string but not in the second: {',
'.join(difference)}")

def display_union_letters(str1, str2):


union = set(str1) | set(str2)
print(f"Union of letters: {', '.join(union)}")

def display_symmetric_difference_letters(str1, str2):


symmetric_difference = set(str1) ^ set(str2)
print(
f"Symmetric difference of letters: {', '.join(symmetric_difference)}")
def main():
while True:
print("\nMenu:")
print("1. Accept two strings")
print("2. Display common letters in two strings")
print("3. Display letters in the first string but not in the second")
print("4. Display union of letters in two strings")
print("5. Display symmetric difference of letters in two strings")
print("6. Exit")
choice = input("Enter your choice: ")

if choice == '1':
global str1, str2
str1, str2 = accept_strings()
elif choice == '2':
if 'str1' in globals() and 'str2' in globals():
display_common_letters(str1, str2)
else:
print("Please accept two strings first.")
elif choice == '3':
if 'str1' in globals() and 'str2' in globals():
display_difference_letters(str1, str2)
else:
print("Please accept two strings first.")
elif choice == '4':
if 'str1' in globals() and 'str2' in globals():
display_union_letters(str1, str2)
else:
print("Please accept two strings first.")
elif choice == '5':
if 'str1' in globals() and 'str2' in globals():
display_symmetric_difference_letters(str1, str2)
else:
print("Please accept two strings first.")
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()
26. Dictionary Operations - Menu Driven
Write a menu-driven program to demonstrate the use of dictionary in python:

o Create key/value pair dictionary

o Update/concatenate and delete item from existing dictionary

o Find a key and print its value

def create_dictionary():
n = int(input("Enter the number of key-value pairs: "))
dictionary = {}
for _ in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
dictionary[key] = value
return dictionary

def update_or_concatenate(dictionary):
key = input("Enter the key to update or add: ")
value = input("Enter the value: ")
dictionary[key] = value
print("Updated dictionary:", dictionary)

def delete_item(dictionary):
key = input("Enter the key to delete: ")
if key in dictionary:
del dictionary[key]
print("Key deleted. Updated dictionary:", dictionary)
else:
print("Key not found.")

def find_key(dictionary):
key = input("Enter the key to find: ")
if key in dictionary:
print(f"Value for key '{key}': {dictionary[key]}")
else:
print("Key not found.")

def main():
dictionary = {}
while True:
print("\nMenu:")
print("1. Create key/value pair dictionary")
print("2. Update/concatenate item in dictionary")
print("3. Delete item from dictionary")
print("4. Find a key and print its value")
print("5. Exit")
choice = input("Enter your choice: ")

if choice == '1':
dictionary = create_dictionary()
elif choice == '2':
update_or_concatenate(dictionary)
elif choice == '3':
delete_item(dictionary)
elif choice == '4':
find_key(dictionary)
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

27. Substring Replacement


Write a python program to check for a substring & replace each of its occurrences
by some other string.

# Program to check for a substring and replace each of its occurrences with
another string

def replace_substring(text, old_substring, new_substring):


"""
Replaces all occurrences of old_substring in text with new_substring.

Parameters:
text (str): The original string.
old_substring (str): The substring to be replaced.
new_substring (str): The string to replace with.

Returns:
str: The modified string with replacements.
"""
return text.replace(old_substring, new_substring)

# Example usage
if __name__ == "__main__":
original_text = input("Enter the original text: ")
substring_to_replace = input("Enter the substring to replace: ")
replacement_string = input("Enter the replacement string: ")

modified_text = replace_substring(
original_text, substring_to_replace, replacement_string)
print("Modified text:", modified_text)

You might also like