我该如何循环呢

时间:2015-10-17 18:19:37

标签: python python-2.7 while-loop

对Python很新,我使用2.7来编写脚本。

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

我需要循环这个 - 如果输入是字母数字或字母,它应该再次请求输入。

我似乎无法找到一种在其中滑动的方法。

(Python新手,请善待!)

3 个答案:

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

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

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

'而真实'永远循环,阻止它的唯一方法就是“打破”#39;在循环中