Page 439 - Computer Science Class 11 With Functions
P. 439
else:
print("You have not entered the correct color")
color = input("Enter the color of the traffic light: ")
trafficLight(color)
Program 26
Write a function calculator() that accepts two numbers as input and a character operator (+, -, *, /) and
returns the sum, difference, product, quotient , and remainder, respectively. An appropriate message should be
displayed if any other character operator is passed as an operator. Make use of the function in a program that reads
the numbers (say, 6 and 7) and the operator (say, *) as user inputs and makes use of the function to display the
output (42).
Ans. def calculator(num1, num2, operator):
'''
Objective : To perform arithmetic operations
Input Parameter : num1,num2 -numeric value and operator-character
Return Value : result
'''
if operator == '+':
result = num1 + num2
operation = "addition"
elif operator == '-':
result = num1 - num2
operation = "subtraction"
elif operator == '*':
result = num1 * num2
operation = "multiplication"
elif operator == '/':
if num2 == 0:
return "Division by zero is not allowed"
result = num1 / num2
operation = "division"
else:
return "Invalid operator. Please use +, -, *, or /."
return f"The {operation} of {num1} and {num2} is {result}"
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operator = input("Enter the operator (+, -, *, /): ")
result = calculator(num1, num2, operator)
print(result)
Practical 437

