Python - ValueError:float()的无效文字:4 /

时间:2014-04-24 16:58:56

标签: python python-2.7 calculator

因此,对于这一门课程,我必须制作一个计算器。 我有一切工作,但对于除法功能,每当我运行它我得到错误

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)

提前致谢

3 个答案:

答案 0 :(得分:1)

如果找不到给定的子字符串,

find()将返回-1。 Python认为-1是一个'truthy'值(而不是像0None[]这些'falsey'这样的值,所以equat.find("\*")在找不到子字符串True时正在评估'*'。你的if语句看起来应该更像:

if equat.find("+") != -1:

发生错误的原因是,当您输入除法等式时,equat.find("\*")求值为-1TruefirstNu将被运算符{{1}调用},'*'评估为fullLine.find(symbol)。 Python通过从字符串末尾向后计数来处理负字符串索引(列表索引以相同的方式处理),因此-1返回firstNu,如果该行是某事,则fullLine[0:-1]将是'4/'比如'4/5'float()不知道如何将'4/'转换为数字,因此会引发您所看到的错误。

您还应该使用

之类的内容替换firstNusecondNumber
def parseNumbers(fullLine, symbol):
    symbol_ind = fullLine.find(symbol)
    if symbol_ind == -1:
        ## do some error handling
    return fullLine[0:symbol_ind].strip(), fullLine[symbol_ind+1:].strip()

答案 1 :(得分:1)

通过首先拆分操作以获得3个组件,然后分派到operator模块中的一个方法,例如:

,可以避免大量的样板文件
from operator import sub, add, div, mul
import re

for line in iter(raw_input, ''): # stop after just enter pressed
    try:
        num1, op, num2 = re.split('([-+/*])', line)
        print {
            '-': sub,
            '+': add,
            '/': div,
            '*': mul
        }[op](float(num1), float(num2))
    except ValueError:
        print line, '-- not valid'

答案 2 :(得分:0)

我建议用以下内容替换firstNusecondNumber

def get_operands(equation, operator):
    return [number.strip() for number in equation.split(operator)]

然后分配如:

val1, val2 = get_operands('345 + 123', '+')

优于您的方法:

  • 支持多个数字的数字
  • 支持数字和运算符之间的间距
相关问题