Hone logo
Hone
Problems

Python Math Operations Mastery

This challenge will test your ability to implement fundamental mathematical operations in Python. You'll create a function that takes two numbers and an operator, then performs the corresponding calculation. This is a foundational skill for many programming tasks involving data manipulation and computation.

Problem Description

Your task is to implement a Python function called perform_operation that accepts three arguments:

  1. num1: The first number (an integer or a float).
  2. num2: The second number (an integer or a float).
  3. operator: A string representing the mathematical operation to perform. This string can be one of the following: '+', '-', '*', '/', '%', or '**'.

The function should return the result of applying the specified operation to num1 and num2.

Key Requirements:

  • Handle addition (+), subtraction (-), multiplication (*), division (/), modulo (%), and exponentiation (**).
  • Ensure that division by zero is handled gracefully. If num2 is 0 and the operator is /, the function should return an informative error message (e.g., "Error: Division by zero").

Expected Behavior:

  • For valid operations and inputs, the function should return the correct numerical result.
  • For division by zero, it should return the specified error message.

Edge Cases to Consider:

  • Division by zero.
  • Inputs being integers or floats.
  • The operator being invalid (though for this challenge, we assume valid operators from the list).

Examples

Example 1:

Input: num1 = 10, num2 = 5, operator = '+'
Output: 15
Explanation: 10 + 5 = 15

Example 2:

Input: num1 = 20, num2 = 4, operator = '/'
Output: 5.0
Explanation: 20 / 4 = 5.0 (Python 3 division results in a float)

Example 3:

Input: num1 = 7, num2 = 0, operator = '/'
Output: Error: Division by zero
Explanation: Attempting to divide by zero is not allowed.

Example 4:

Input: num1 = 3, num2 = 3, operator = '**'
Output: 27
Explanation: 3 raised to the power of 3 (3^3) is 27.

Constraints

  • num1 and num2 will be numeric types (integers or floats).
  • The operator string will be one of '+', '-', '*', '/', '%', or '**'.
  • The function should return a numerical type (int or float) for valid operations, or a string for error conditions.

Notes

  • Consider how Python handles integer division versus float division in Python 3.
  • You can use an if-elif-else structure or a dictionary to map operators to their corresponding actions.
  • Remember to check for the division by zero condition before attempting the division.
Loading editor...
python