无法将字符串转换为 int 或 float

时间:2021-07-13 16:51:38

标签: python

所以我能够在你们的帮助下解决第一个问题,但是现在程序运行没有任何错误,它没有正确计算平均值,我不知道为什么。这是它的样子:

def calcAverage():
with open('numbers.dat', 'r') as numbers_file:
    numbers = 0
    amount = 0

    for line in numbers_file:
        amount = amount + float(line)
        numbers += 1


average = amount / numbers
print("The average of the numbers in the file is:",average)

3 个答案:

答案 0 :(得分:2)

在检查 line 中的 line 是否为空之后,您正在重新分配 whilewhile 测试正在测试文件中的前一行。

所以当你读到最后时,你读到一个空行并尝试将它添加到 amount 中,但得到一个错误。

您也永远不会添加第一行,因为您在循环之前阅读了它并且永远不会将其添加到 amount

使用 for 循环代替 while,它会在到达结束时自动停止。

def calcAverage():
    with open('numbers.dat', 'r') as numbers_file:
        numbers = 0
        amount = 0
    
        for line in numbers_file:
            amount = amount + float(line)
            numbers += 1
    
    average = amount / numbers
    print("The average of the numbers in the file is:",average)

如果您确实想使用 while 循环,请这样做:

while True:
    line = numbers_file.readline()
    if not line:
        break

    # rest of loop

答案 1 :(得分:0)

错误表明您在 line 中有空字符串。

你可以用 float('')

得到同样的错误

您以错误的顺序运行代码 - 在转换前一行之前读取了新行。
你应该剥离线,因为它仍然有 \n

你需要

line = numbers_file.readline()
line = line.strip()  # remove `\n` (and `\t` and spaces)

while line != '':

    # convert current line
    amount = amount + float(line)  

    numbers += 1

    # read next line
    line = numbers_file.readline()
    line = line.strip()  # remove `\n` (and `\t` and spaces)

您也可以为此使用 for 循环

numbers = []

for line in numbers_file:
    line = line.strip()  # remove `\n` (and `\t` and spaces)
    if line:
       numbers.append( float(line) )
    #else:
    #   break

average = sum(numbers) / len(numbers)

这可以减少到

numbers = [float(line) for line in numbers_file if line.strip() != '']

average = sum(numbers) / len(numbers)

答案 2 :(得分:0)

其他答案说明了如何逐行读取文件。 其中一些处理诸如到达文件尾 (EOF) 和用于转换为浮点数的无效输入等问题。

由于任何 I/O 和 UI 都可能提供无效输入,因此我想在按预期处理输入之前强调验证。

验证

对于从输入控制台或类似文件中读取的每一行,您应该考虑进行验证。

  • 如果字符串为会怎样? Converting an empty string input to float
  • 如果字符串包含特殊字符会怎样?喜欢commented by Mat
  • 如果数字不符合您预期的float会怎样? (取值范围,小数精度)
  • 如果没有读取或到达文件尾会发生什么? (空文件或 EOF)

建议:为了使其健壮,预期输入错误并捕获它们。

(a) 在 Python 中使用 try-except 构造进行错误处理:

for line in numbers_file:
    try:
        amount = amount + float(line)
        numbers += 1
    except ValueError:
        print "Read line was not a float, but: '{}'".format(line)

(b) 提前测试输入: 以更简单的方式,您还可以使用基本的 if 语句手动测试,例如:

if line == "":  # on empty string received
    print("WARNING: read an empty line! This won't be used for calculating average.")  # show problem and consequences
    continue  # stop here and continue with next for-iteration (jump to next line)