Python Practical Exam Question Bank Solution
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
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
students = {}
while True:
print("\nStudent Record Keeper")
8. Pattern Printer
Print triangle/star patterns using loops
def triangle_pattern(n):
for i in range(1, n + 1):
print("*" * i)
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
# 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
# Example Usage
sort_cities("cities.txt", "sorted_cities.txt")
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()
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.")
def print_divisible_by_4(n):
for i in range(1, n + 1):
if i % 4 == 0:
print(i)
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.")
def calculator():
while True:
print("\nSimple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
if choice == '5':
print("Exiting the calculator. Goodbye!")
break
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()
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)
if __name__ == "__main__":
count_words_and_characters()
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)}")
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 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 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
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:
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()
# Program to check for a substring and replace each of its occurrences with
another string
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)