Python - 输入验证

时间:2013-10-03 10:56:17

标签: python validation input python-3.x python-3.3

我希望在继续之前创建需要用户输入大于2的整数的代码。我正在使用python 3.3。这是我到目前为止所做的:

def is_integer(x):
    try:
        int(x)
        return False
    except ValueError:
        print('Please enter an integer above 2')
        return True

maximum_number_input = input("Maximum Number: ")

while is_integer(maximum_number_input):
    maximum_number_input = input("Maximum Number: ")

    print('You have successfully entered a valid number')

我不确定的是如何在整数必须大于2的条件下最好。我刚开始学习python但是想养成良好的习惯。

7 个答案:

答案 0 :(得分:5)

这应该做的工作:

def valid_user_input(x):
    try:
        return int(x) > 2
    except ValueError:
        return False

maximum_number_input = input("Maximum Number: ")

while valid_user_input(maximum_number_input):
    maximum_number_input = input("Maximum Number: ")
    print("You have successfully entered a valid number")

甚至更短:

def valid_user_input():
    try:
        return int(input("Maximum Number: ")) > 2
    except ValueError:
        return False

while valid_user_input():
    print('You have successfully entered a valid number')

答案 1 :(得分:1)

def take_user_in():
    try:
        return int(raw_input("Enter a value greater than 2 -> "))  # Taking user input and converting to string
    except ValueError as e:  # Catching the exception, that possibly, a inconvertible string could be given
        print "Please enter a number as" + str(e) + " as a number"
        return None


if __name__ == '__main__':  # Somethign akin to having a main function in Python

    # Structure like a do-whole loop
    # func()
    # while()
    #     func()
    var = take_user_in()  # Taking user data
    while not isinstance(var, int) or var < 2:  # Making sure that data is an int and more than 2
        var = take_user_in()  # Taking user input again for invalid input

    print "Thank you"  # Success

答案 2 :(得分:1)

我的看法:

from itertools import dropwhile
from numbers import Integral
from functools import partial
from ast import literal_eval

def value_if_type(obj, of_type=(Integral,)):
    try:
        value = literal_eval(obj)
        if isinstance(value, of_type):
            return value
    except ValueError:
        return None

inputs = map(partial(value_if_type), iter(lambda: input('Input int > 2'), object()))

gt2 = next(dropwhile(lambda L: L <= 2, inputs))

答案 3 :(得分:0)

def check_value(some_value):
    try:
       y = int(some_value)
    except ValueError:
       return False
    return y > 2 

答案 4 :(得分:0)

这验证输入是一个整数,但是拒绝像整数那样看起来的值(如3.0):

def is_valid(x):
    return isinstance(x,int) and x > 2

x = 0
while not is_valid(x):
    # In Python 2.x, use raw_input() instead of input()
    x = input("Please enter an integer greater than 2: ")
    try:
        x = int(x)
    except ValueError:
        continue

答案 5 :(得分:0)

希望这有帮助

module Web
  class API < Grape::API
    prefix 'api'
    mount Web::V1::Root
    # mount API::V2::Root (next version)
  end
end
  • str.isdidig()将消除包含非整数,浮点数('。')和负数(' - ')(小于2)的所有字符串
  • int(user_input)确认它是一个大于2的整数
  • 如果两者都为True,则
  • 返回True

答案 6 :(得分:0)

使用其他答案中显示的int()内置函数的问题是它将浮点数和布尔值转换为整数,因此这并不是检查您的参数是否为整数。

很想单独使用内置的isinstance(value, int)方法,但不幸的是,如果传递了布尔值,它将返回True。因此,如果您想严格类型检查,这是我简短而又可爱的Python 3.7解决方案:

def is_integer(value):
    if isinstance(value, bool):
        return False
    else:
        return isinstance(value, int)

结果:

is_integer(True)  --> False
is_integer(False) --> False
is_integer(0.0)   --> False
is_integer(0)     --> True
is_integer((12))  --> True
is_integer((12,)) --> False
is_integer([0])   --> False

等...