2013-06-03 97 views
-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" 

我看不到問題。
爲什麼它不進入一個循環?
不打印什麼,只是被卡住。爲什麼我的代碼不能進入循環?

+0

'flag!= False'與'flag'相同。 – 2013-06-03 13:28:40

+0

同樣,'is_number(numInput)== TRUE'應該只是'is_number(numInput)'。 –

+0

您可能想告訴我們您的代碼應該做什麼。 – georg

回答

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 
0

試試這個:

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

也在循環結束後,該值將被賦值給'numInput'變量,以便您可以使用它的腳本。 – abhishekgarg

相關問題