2016-11-06 148 views
0
print('Enter a mathematical expression: ') 
expression = input() 
space = expression.find(' ') 
oprand1 = expression[0 : space] 
oprand1 = int(oprand1) 
op = expression.find('+' or '*' or '-' or '/') 
oprand2 = expression[op + 1 : ] 
oprand2 = int(oprand2) 
if op == '+': 
ans = int(oprand1) + int(oprand2) 
print(ans) 

因此可以說用戶在每個字符之間輸入2 + 3的空格。我怎樣才能打印2 + 3 = 5?我需要代碼來處理所有操作。評估一個數學表達式(python)

+0

您使用的是哪個版本的python? http://stackoverflow.com/questions/1093322/how-do-i-check-what-version-of-python-is-running-my-script – AbrahamB

+0

Anaconda spyder –

+0

你可以打印'import sys'的結果嗎' sys.version' – polka

回答

0

我會建議沿着這些線的東西,我認爲你 可能超過複雜的解析輸入表達式的值。

可以簡單地調用對輸入字符串.split()方法,它由缺省 分裂上的空間「」,所以字符串「1 + 5」將返回[「1」,「+」,' 5' ]。 然後,您可以將這些值解包到您的三個變量中。

print('Enter a mathematical expression: ') 
expression = input() 
operand1, operator, operand2 = expression.split() 
operand1 = int(operand1) 
operand2 = int(operand2) 
if operator == '+': 
ans = operand1 + operand2 
print(ans) 
elif operator == '-': 
    ... 
elif operator == '/': 
    ... 
elif operator == '*': 
    ... 
else: 
    ... # deal with invalid input 

print("%s %s %s = %s" % (operand1, operator, operand2, ans)) 
+0

您能否向我解釋3個點的含義以及「%s%s%s =%s」是什麼意思?當然是 –

+0

!我只是做了......以表明你可以填寫像上一個那樣的部分。這不是實際的代碼。 – chatton

+0

%s是一個格式字符串,您可以提供值(在本例中爲運算符,操作數和答案)。每個%s對應於您在%之後傳入的值。起初我發現它們很混亂。有一個string.format方法,我認爲這實際上是更好的做法。所以你也可以閱讀它 – chatton