我正在编写一个python代码,用户可以输入尽可能多的数字,直到他们单击Enter而不输入数字。它会进行计算以找到最大值,最小值,平均值和总计。
但是我一直遇到这个错误。
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)
编辑:我修复了它,感谢评论中的人。但是,有一个新错误
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'
正如在其他答案中指出的那样,您将输入的字符串与空格而不是空字符串进行比较。但是即使纠正了错误,用户也可以输入错误的格式化数字。这些案例被命名为“异常”,您应该使用try/except
构造来处理它。还有一些max
,min
和sum
功能。顺便说一句,您可以使用str.join
方法将列表连接到字符串中。
我会建议这样的代码:
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句