因此,對於這一門課程,我必須製作一個計算器。 我所擁有的一切工作,但對於分頻功能,每當我運行它,我得到的錯誤Python - ValueError:無效文字float():4/
Traceback (most recent call last):
File "C:\Python27\Calculator.py", line 43, in <module>
val3 = Mult(val1, val2)
File "C:\Python27\Calculator.py", line 17, in Mult
val1 = float(val1)
ValueError: invalid literal for float(): 4/
這裏是我的代碼,我意識到,我可能會使用這樣的東西,如獲得操作數超出了許多不正當手段字符串,但我真的不知道任何其他方式。
def firstNu(fullLine, symbol):
return fullLine[0:fullLine.find(symbol)].strip()
def secondNumber(fullLine, symbol):
return fullLine[fullLine.find(symbol) + len(symbol) : len(fullLine)].strip()
def Add(val1, val2):
val1 = float(val1)
val2 = float(val2)
val3 = val1 + val2
return val3
def Sub(val1, val2):
val1 = float(val1)
val2 = float(val2)
val3 = val1 - val2
return val3
def Mult(val1, val2):
val1 = float(val1)
val2 = float(val2)
val3 = val1 * val2
return val3
def Div(val1, val2):
val1 = val1
val2 = val2
val3 = val1/val2
return val3
while True:
equat = raw_input()
if equat.find("+") == 1:
operand = ('+')
val1 = firstNu(equat, operand)
val2 = secondNumber(equat, operand)
val3 = Add(val1, val2)
elif equat.find("-") == 1:
operand = ('-')
val1 = firstNu(equat, operand)
val2 = secondNumber(equat, operand)
val3 = Sub(val1, val2)
elif equat.find("*"):
operand = ('*')
val1 = firstNu(equat, operand)
val2 = secondNumber(equat, operand)
val3 = Mult(val1, val2)
elif equat.find("/"):
operand = ('/')
val1 = firstNu(equat, operand)
val2 = secondNumber(equat, operand)
val3 = Div(val1, val2)
print(val1, operand, val2, "=", val3)
在此先感謝
很多問題:由於您使用'equat.find(...)== 1',您只支持1位數字。像'val1 = val1'這樣的行應該是不必要的。你的'firstNu'和'secondNumber'函數應該被合併成一個更好的函數來返回多個值。 –