2016-08-23 42 views
-2

如何讓用戶輸入值並接收答案,同時將「x + xy + y」的值保留在一行上?在一行上打印多條語句以輸入

print("Calculator") 

x = input("") 
xy = input("") 
y = input("") 

if xy == "+": 
    print(x+y) 
elif xy == "-": 
    print(x-y) 
elif xy == "*": 
    print(x*y) 
elif xy == "/": 
    print(x/y) 
+1

只使用一個'input',然後使用正則表達式或類似的語法來解析字符串。另外,你是否希望用戶在x,xy和y之間按Enter? –

+1

這段代碼很可能並沒有達到你期望的程度,因爲你並沒有轉換字符串,即:1 + 2 = 12 – danielfranca

+0

[Python創建計算器]的可能重複(http://stackoverflow.com/questions/13116167/python-creating-a-calculator) – log0

回答

1

我建議使用一個單一的input語句,然後使用一個簡單的regular expression字符串解析成xy和運營商。例如,這種模式:(\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)) 
0

這是另一種可能性。

raw = raw_input("Calculator: ") 
raw1 = raw.split(" ") 
x = int(raw1[0]) 
xy = raw1[1] 
y = int(raw1[2]) 

if xy == "+": 
    print raw, "=", x + y 
elif xy == "-": 
    print raw, "=", x-y 
elif xy == "/": 
    print raw, "=", x/y 
elif xy == "*": 
    print raw, "=", x*y 
0

你可以輸入這樣的:

cal = input("Calculator: ").strip().split() 
x, xy, y = int(cal[0]), cal[1], int(cal[2]) 

然後你就可以處理你的輸入數據。