我不确定代码是否有问题,因为我只是刚开始使用python但是当输入错误的值时输出“ValueError:无法将字符串转换为float:'(错误值)' ”。但是我希望它输出“无效字符。请再试一次。”然后让循环从一开始就继续回来,我无法弄清楚我可以改变什么,所以对所需内容的解释也会很好。
ListOfNumbers = []
while True:
Number = float(input("Enter a number >>"))
if Number == 0:
print ("End.")
break
try:
ListOfNumbers.append(int(Number))
Average = float(sum(ListOfNumbers))/len(ListOfNumbers)
except ValueError:
print ("Invalid Character/s. Please Try Again.")
continue
print ("The total value is", sum(ListOfNumbers))
print ("The average value is", Average)
print ("The highest value is", max(ListOfNumbers))
print ("The lowest value is", min(ListOfNumbers))
ListOfNumbers.sort()
print ("List of numbers", ListOfNumbers)
答案 0 :(得分:1)
引入输入的行抛出ValueError
异常。移动try
块以捕获异常。
while True:
try:
Number = float(input("Enter a number >>"))
if Number == 0:
print ("End.")
break
ListOfNumbers.append(int(Number))
Average = float(sum(ListOfNumbers))/len(ListOfNumbers)
except ValueError:
print ("Invalid Character/s. Please Try Again.")
continue