我建議使用一個單一的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