2015-10-17 131 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