简体   繁体   English

如何修复“ValueError:无法将字符串转换为浮点数”?

[英]How to fix “ValueError: could not convert string to float”?

I'm writing a python code where the use can input as many numbers until they click enter without entering a number.我正在编写一个 python 代码,其中用户可以输入尽可能多的数字,直到他们单击输入而不输入数字。 The it does calculations to find the max, min, average, and total.它进行计算以找到最大值、最小值、平均值和总数。

But I keep running into that error.但我一直遇到这个错误。

numberList = []

while True:
  enterNumber = input("Please enter a number (RETURN/ENTER when done): ")
  if enterNumber == " ":
    break
  convertFloat = float(enterNumber)
  numberList.append(convertFloat)

theMax = numberList[0]
theMin = numberList[0]
theTotal = 0.0

for value in numberList:
  if value > theMax:
    theMax = value

  if value < theMin:
    themin = value

  theTotal = theTotal + value

average = theTotal / len(numberList)

print("The numbers entered were: ")
for numbers in numberList:
    print(" ", numbers)
print("Max value was: " + str(theMax))
print("Min value was: " + str(theMin))
print("The total is: " + str(theTotal))
print("Average value was: ") + str(avg)

EDIT: I fixed it thanks to the person in the comments.编辑:感谢评论中的人,我修复了它。 However, there is a new error但是,有一个新的错误

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    print("Average value was: ") + str(average)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

This error occurs because the program fails to convert the str value to float value.出现此错误是因为程序未能将str值转换为float值。

Why?为什么? your str value isn't in a float format, maybe it contains only characters and words but you need to input float string value and then the program will cast it into float successfully.您的str值不是浮点格式,可能只包含字符和单词,但您需要输入float字符串值,然后程序将成功将其转换为浮点数。

If you want to handle this situation learn about try, except .如果您想处理这种情况,请了解try, except .

The error comes from these lines:错误来自以下几行:

enterNumber = input("Please enter a number (RETURN/ENTER when done): ")
if enterNumber == " ":
    break
convertFloat = float(enterNumber)

When done, the user inputs blank which corresponds to "" .完成后,用户输入对应于""的空白。 However, your code checks only for " " (a blank space) and so the input "" gets passed to float and raises an error.但是,您的代码仅检查" " (空格),因此输入""被传递给float并引发错误。 A quick fix is to change if enterNumber == " ": to if enterNumber == "": .一个快速的解决方法是将if enterNumber == " ":更改为if enterNumber == "":

Also there's a further error down at line 31 where you call variable avg which is not referenced.在第 31 行还有一个错误,您在其中调用未引用的变量avg I'd change it to average .我会将其更改为average

As it was noted in the other answers, you compare an entered string with a space instead of an empty string.正如其他答案中所述,您将输入的字符串与空格而不是空字符串进行比较。 But even with the mistake fixed, the user can enter a wrong formatted number.但即使错误已修复,用户仍可能输入格式错误的数字。 The cases are named as Exceptions, and you should handle it using try/except construction.这些案例被命名为异常,您应该使用try/except构造来处理它。 Also there are max , min and sum functions.还有maxminsum函数。 By the way, you can use str.join method to join a list into a string.顺便说一句,您可以使用str.join方法将列表加入字符串。

I would suggest such a code:我会建议这样的代码:

numberList = []

while True:
    enterNumber = input("Please enter a number (RETURN/ENTER when done): ")
    print(enterNumber)
    if not enterNumber:
        break
    try:
        convertFloat = float(enterNumber)
        numberList.append(convertFloat)
    except ValueError:
        print("Your entered a wrong formatted number, try one more time.")

theMax = max(numberList)
theMin = min(numberList)
theTotal = sum(numberList)
average = theTotal / len(numberList)

print("The numbers entered were: ")
print(" ".join(map(str, numberList)))
print("Max value was: " + str(theMax))
print("Min value was: " + str(theMin))
print("The total is: " + str(theTotal))
print("Average value was: " + str(average))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复“ValueError:无法将字符串转换为浮点数” - How to fix “ValueError: could not convert string to float” 如何修复 ValueError :无法将字符串转换为浮点数:在 Python 中 - how to fix ValueError :could not convert string to float: in Python 如何修复“ValueError:无法将字符串转换为浮点数:&#39;East&#39;”(Python) - How to fix "ValueError: could not convert string to float: 'East'" (Python) 如何使用tkinter修复Python中的“ ValueError:无法将字符串转换为float:” - How to fix “ValueError: could not convert string to float:” in Python with tkinter 如何修复此错误:ValueError:无法将字符串转换为浮点数:'A' - How to fix this error: ValueError: could not convert string to float: 'A' 如何修复 ValueError: could not convert string to float: in python - How to fix the ValueError: could not convert string to float: in python 如何解决此ValueError:无法将字符串转换为float? - How to workaround this ValueError: could not convert string to float? ValueError:无法将字符串转换为float:&#39; &#39; - ValueError: could not convert string to float: '���' ValueError: 无法将字符串转换为浮点数:&#39;-&#39; - ValueError: could not convert string to float: '-' ValueError:无法将字符串转换为浮点数:''" - ValueError: could not convert string to float: '' "
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM