如何通过不输入值来打破 while 循环?

How to break a while loop by not entering a value?

我正在尝试编写一个非常简单的程序,它使用 while 循环读取一系列 float 值并计算它们的平均值,当用户只需按下 输入而不提供值。

这是我目前的情况,但显然会产生错误:

total = 0
num_values = 0
a = 0

while a != None:
    a = raw_input("Number: ")
    total = total + float(a)
    num_values = num_values + 1

print "The number of values entered was ",num_values
print "The mean is ",total/num_values

错误:

    total = total + float(a)
ValueError: could not convert string to float: 

我明白为什么会收到此错误,但我不确定该怎么做。另外,我知道这可以通过列表或 tryexcept 来完成,但我需要使用 while 循环来完成。

您需要测试空字符串,并在转换为浮点数之前执行此操作:

while True:
    a = raw_input("Number: ")
    if not a:
        break
    total = total + float(a)
    num_values = num_values + 1

这个循环简直就是死循环,执行一个break退出循环