为什么我的代码不进入循环?

时间:2013-06-03 13:26:46

标签: python loops

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"

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

试试这个:

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