Exercise: Calculator

Exercise on creating a calculator.

We'll cover the following

Task

A data analyst wants to do mathematical operations on a series of values. He was able to extract multiple operands and label them as left and right operands. He extracted operators too. The only task left is the operation itself. He converted types of operands to number, but left the operator to the string type. Your task: to write code which does the mathematical operation depending on the value of the operator.

Problem statement

You are given three variables named left_operand, right_operand, and operator. Write code for operator values so that each value does the following:

  • '+': Add left_operand to right_operand and assign the result to ans.
  • '-': Subtract left_operand from right_operand and assign the result to ans.
  • '*': Multiply left_operand with right_operand and assign the result to ans.
  • '/': Divide left_operand with right_operand and assign the result to ans.
  • For any other operator, assign NaN to ans.

Remember, there are a lot of ifs to what the operator is. Find a solution to all ifs.

Good luck!

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy