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:
'+'
: Addleft_operand
toright_operand
and assign the result toans
.'-'
: Subtractleft_operand
fromright_operand
and assign the result toans
.'*'
: Multiplyleft_operand
withright_operand
and assign the result toans
.'/'
: Divideleft_operand
withright_operand
and assign the result toans
.- For any other operator, assign
NaN
toans
.
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