Python - ValueError: 无法将字符串转换为浮点数:4/

-1 投票
3 回答
1721 浏览
提问于 2025-04-18 04:07

我在上一个课程中需要做一个计算器。现在其他功能都正常,但在除法功能上,每次运行时都会出现错误。

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

我建议把 firstNusecondNumber 替换成下面这样的:

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

然后可以这样赋值:

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

这种方法比你之前的方法有以下优点:

  • 可以处理多位数的数字
  • 可以处理数字和运算符周围的空格
1

find() 方法会在找不到指定的子字符串时返回 -1。在 Python 中,-1 被认为是“真”的值(与 0None[] 这些被认为是“假”的值相对),所以当你用 equat.find("\*") 查找子字符串 '*' 时,如果没有找到,它的结果会被当作 True 来处理。你的 if 语句应该像这样:

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

这个错误发生的原因是,当你输入一个除法表达式时,equat.find("\*") 返回 -1,这被视为 True,于是 firstNu 被调用时使用了操作符 '*',而 fullLine.find(symbol) 也返回 -1。Python 处理负数字符串索引时是从字符串的末尾往回数(列表索引也是这样处理),所以 firstNu 返回 fullLine[0:-1],如果这一行是 '4/5',那么结果就是 '4/'。而 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

你可以通过先根据操作类型进行拆分,来避免很多重复的代码。这样可以得到三个部分,然后再调用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'

撰写回答