Tutorialspoint
Problem
Solution
Submissions

Implement a Simple Calculator Using Functions

Certification: Intermediate Level Accuracy: 75% Submissions: 4 Points: 15

Write a Python program that implements a simple calculator with functions for addition, subtraction, multiplication, and division. The program should take two numbers and an operator as input and return the result.

Example 1
  • Input: 10, 5, "+"
  • Output: 15
Example 2
  • Input: 10, 5, "*"
  • Output: 50
Constraints
  • Supported operators: "+", "-", "*", "/"
  • -10^9 ≤ operands ≤ 10^9
  • Handle division by zero
  • Time Complexity: O(1)
  • Space Complexity: O(1)
MapFunctions / MethodsFile Handling WiproCognizant
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create separate functions for each operation
  • Use a dictionary to map operators to functions
  • Handle edge cases like division by zero
  • Validate input type and operation

Steps to solve by this approach:

  • The calculator function is called with num1 = 10, num2 = 5, and operator = "+".
  • The operations dictionary maps "+" to the add function.
  • operations["+"](10, 5) calls the add function with a = 10 and b = 5.
  • The add function returns 10 + 5 = 15.
  • The calculator function returns 15.
  • print(result) prints 15 to the console

Submitted Code :