如何验证数字的python raw_input

时间:2016-04-21 18:24:37

标签: python

# Validating for only numbers in python one after another(in sequence)

a = raw_input()

#if a is a number then it should take next raw_input i.e., 'b' else it should ask for 'a' again

b = raw_input()

#if b is a number then it should take next raw_input i.e., 'c' else it should ask for 'b' again

c = raw_input()

#if c is a number then it should take next raw_input i.e., 'd' else it should ask for 'c' again

## This should be done upto 'e'

2 个答案:

答案 0 :(得分:1)

使用a.isdigit()验证字符串a是否为数字

  

str.isdigit()   如果字符串中的所有字符都是数字且至少有一个字符,则返回true,否则返回false。

答案 1 :(得分:0)

使用if..else构造进行条件检查,并将此post引用进行整数检查。

修改1

我还没有执行它,但您可以尝试以下操作,看看它是否有效 -

def ask(text):
    temp = raw_input(text)
    try:
        retVal = int(temp)
        return retVal
    except ValueError:
        return False

a = False
b = False
c = False

while not a:
    a = ask("Enter A:")
    if a == False:
        continue
    while not b:
        b = ask("ENter B:")
        if b == False:
            continue
        while not c:
            c = ask("Enter C:")