我建议使用一个单一的input
语句,然后使用一个简单的regular expression字符串解析成x
,y
和运营商。例如,这种模式:(\d+)\s*([-+*/])\s*(\d+)
。这里,\d+
是指“一个或多个数字”,\s*
手段“零个或多个空格”,和[-+*/]
手段“任何这四个符号。内(...)
各部分可以稍后被提取。
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")
可选地四个if/elif
,你还可以创建一个字典,映射运算符号功能:
operators = {"+": lambda n, m: n + m}
然后就是从那个字典正确的功能,并将其应用到操作数:
print(operators[op](x, y))
只使用一个'input',然后使用正则表达式或类似的语法来解析字符串。另外,你是否希望用户在x,xy和y之间按Enter? –
这段代码很可能并没有达到你期望的程度,因为你并没有转换字符串,即:1 + 2 = 12 – danielfranca
[Python创建计算器]的可能重复(http://stackoverflow.com/questions/13116167/python-creating-a-calculator) – log0