I'd suggest using a single input
statement and then using a simple regular expression to parse the string into x
, y
and the operator. For example, this pattern: (\d+)\s*([-+*/])\s*(\d+)
. Here, \d+
means "one or more digits", \s*
means "zero or more spaces", and [-+*/]
means "any of those four symbols. The parts within (...)
can later be extracted.
import re
expr = input() # get one input for entire line
m = re.match(r"(\d+)\s*([-+*/])\s*(\d+)", expr) # match expression
if m: # check whether we have a match
x, op, y = m.groups() # get the stuff within pairs of (...)
x, y = int(x), int(y) # don't forget to cast to int!
if op == "+":
print(x + y)
elif ...: # check operators -, *, /
...
else:
print("Invalid expression")
Alternatively to four if/elif
, you could also create a dictionary, mapping operator symbols to functions:
operators = {"+": lambda n, m: n + m}
And then just get the right function from that dict and apply it to the operands:
print(operators[op](x, y))