Exercise: Calculator
Understand how to use if-else statements to perform mathematical operations based on operator values. Learn to add, subtract, multiply, and divide numbers conditionally, and handle invalid operators by assigning NaN.
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_operandtoright_operandand assign the result toans.'-': Subtractleft_operandfromright_operandand assign the result toans.'*': Multiplyleft_operandwithright_operandand assign the result toans.'/': Divideleft_operandwithright_operandand assign the result toans.- For any other operator, assign
NaNtoans.
Remember, there are a lot of ifs to what the operator is. Find a solution to all ifs.
Good luck!