2015-10-17 58 views
-4

對Python來說很新穎,我使用2.7來編寫腳本。我該如何循環這個

a = raw_input("Input number or decimal only") 
Try: 
    Y = float(a) 
    print a 
except ValueError: 
    print "wrong input, try again" 

我需要循環 - 如果輸入是字母數字或字母,它應該再次要求輸入。

我似乎無法找到一種方法在它的while循環中滑動。

(Python的新手,請善待!)

+0

有沒有中 '休息'你複製粘貼你的代碼或重新輸入它?因爲這個代碼不會運行。 – idjaw

+0

你有沒有嘗試用'while True:'塊封裝整個事物? –

回答

0
correct = False 
a = "" 
while not correct: 
    a = raw_input("Input number or decimal only") 
    correct = a.isalnum() 
    if not correct: 
     print "wrong input, try again" 
print a 
+0

我正在顯示OP在哪裏插入循環:) –

+1

那永遠不會從循環中斷開,這有什麼意義? – Tim

+0

沒有仔細閱讀問題。編輯。 –

0
input = "%" # Set to be non alphanumeric so loop starts 
while not input.isalnum(): 
    input = raw_input("Input number or decimal only > ") 
    if not input.isalnum(): 
     print ("Invalid Input, try again") 
    else: 
     print (input) 
0
while True: # Loops! 
    a = raw_input("Input number or decimal only\n") 
    try: 
     Y = float(a) 
     print a 
     break # Interrupts the loop if the input was a number 
    except ValueError: 
     print "wrong input, try again" 

'而真正的' 循環永遠,阻止它的唯一辦法是循環

+0

啊,謝謝! 我覺得這很容易。感謝幫助:) – Doran

+0

沒問題!詢問你是否需要其他東西 – Mark