Activity-based Questions · Q5
Q.Create a menu driven program using user defined functions to implement a calculator that performs the following:
a) Basic arithmetic operations(+,-,*,/)
b) log10(x),sin(x),cos(x)
Yanam BieapTextbookSubjective· 5mImportance★★★★★est
90% · 36/40 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Define one small function per arithmetic operation, use the math module for log10/sin/cos, and run an "until Exit" menu loop that reads the user's choice and calls the matching function — a standard menu-driven calculator.
The idea. A menu-driven program is a dispatcher: an endless while loop shows options, reads a choice, and routes to the right function. Writing each operation as its own user-defined function keeps the menu logic and the arithmetic cleanly separated — and part (b) simply reuses ready-made functions from the math module instead of reinventing them.
import math
# --- part (a): basic arithmetic operations -------------------------
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: division by zero"
return x / y
# --- the menu loop --------------------------------------------------
while True:
print()
print("======== CALCULATOR ========")
print("1. Add 5. log10(x)")
print("2. Subtract 6. sin(x)")
print("3. Multiply 7. cos(x)")
print("4. Divide 8. Exit")
choice = int(input("Enter your choice (1-8): "))
if choice == 8:
print("Goodbye!")
break
elif choice in (1, 2, 3, 4):
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
if choice == 1:
print("Result =", add(x, y))
elif choice == 2:
print("Result =", subtract(x, y))
elif choice == 3:
print("Result =", multiply(x, y))
else:
print("Result =", divide(x, y))
elif choice in (5, 6, 7): # part (b): math functions
x = float(input("Enter the value of x: "))
if choice == 5:
print("Result =", math.log10(x))
elif choice == 6:
print("Result =", math.sin(x))
else:
print("Result =", math.cos(x))
else:
print("Invalid choice — please pick 1 to 8.")
Sample run
======== CALCULATOR ========
1. Add 5. log10(x)
2. Subtract 6. sin(x)
3. Multiply 7. cos(x)
4. Divide 8. Exit
Enter your choice (1-8): 1
Enter first number: 12
Enter second number: 8
Result = 20.0
Enter your choice (1-8): 5 …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.