-1
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False  


flag = True
while flag != False:
    numInput = raw_input("Enter your first number: ")
    if is_number(numInput):
        numInput = float(numInput)
        flag = True
        break
    else:
        print "Error, only numbers are allowed"

我没有看到问题。
为什么不进入循环?
不打印任何东西,只是卡住了。

4

2 回答 2

1

flag = False这里不需要:

else:
    print "Error, only numbers are allowed"
    flag = False  <--- remove this

只需使用:

while True:
    numInput = raw_input("Enter your first number: ")
    if is_number(numInput):
        numInput = float(numInput)
        break
    else:
        print "Error, only numbers are allowed"

演示:

Enter your first number: foo
Error, only numbers are allowed
Enter your first number: bar
Error, only numbers are allowed
Enter your first number: 123
于 2013-06-03T13:28:26.343 回答
0

尝试这个:

while True:
    numInput = raw_input("Enter your first number: ")    
    try:
        numInput = float(numInput)
        break
    except:
        print "Error, only numbers are allowed"
于 2013-06-03T13:35:24.370 回答