What I tried to do:
Create a calculator application. Write code that will take two numbers and an operator in the format: N1 OP N2, where N1 and N2 are floating point or integer values, and OP is one of the following: +, -, , /, %, *, representing addition, subtraction, multiplication, division, modulus/remainder, and exponentiation, respectively, and displays the result of carrying out that operation on the input operands.
What I was able to come up with:
def calculator(n1,op,n2):
n1 = float(n1)
n2 = float(n2)
if op == "+":
return (n1 + n2)
elif op == "-":
return (n1 - n2)
elif op == "*":
return (n1 * n2)
elif op == "/":
return (n1 / n2)
elif op == "%":
return (n1 % n2)
elif op == "**":
return (n1 ** n2)
It works. But there might be 2 potential improvements:
right now one has to use double quotes(
"") when entering the operator, for example, calculator(3,"+",3). Otherwise the interpreter returns aSyntaxErrorpop-up. I tried to changeif op == "+":intoif op == +:, but then the interpreter returns a SyntaxError, highlighting the:after the+.right now the function converts all kinds of number input into
float(), even if integer was taken as input. How to let the function itself determine whether the input is integer or floating point, and convert it accordingly?
I read the Documentation on Functions, but it only talked about several types of arguments, and none of them seem to help solving the current problems. I'm sure this is pretty basic stuff, but as a beginner I tried and wasn't able to figure it out.
calculatorto be called?calculator(1, +, 2)? You can't do that. Write a parser and just pass in a string:calculator('1 + 2').floatonn1andn2...