Python - 输入验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19157374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Input Validation
提问by nathangrand
I'm looking to create code which requires an integer greater than 2 to be input by a user before continuing. I'm using python 3.3. Here's what I have so far:
我正在寻找创建代码,该代码要求用户在继续之前输入大于 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')
What I'm not sure about is how best to put in the condition that the integer must be greater than 2. I've only just started learning python but want to get into good habits.
我不确定的是如何最好地设置整数必须大于 2 的条件。我刚刚开始学习 python,但想养成良好的习惯。
回答by Games Brainiac
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
回答by Roman Bodnarchuk
This should do the job:
这应该可以完成这项工作:
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")
Or even shorter:
或者更短:
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')
回答by Burhan Khalid
def check_value(some_value):
try:
y = int(some_value)
except ValueError:
return False
return y > 2
回答by chepner
This verifies that the input is an integer, but does reject values that looklike integers (like 3.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
回答by Jon Clements
My take:
我的看法:
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))
回答by Art Knipe
Hope this helps
希望这可以帮助
import str
def validate(s):
return str.isdigit(s) and int(s) > 2
- str.isdidig() will eliminate all strings containing non-integers, floats ('.') and negatives ('-') (which are less than 2)
- int(user_input) confirms that it's an integer greater than 2
- returns True if both are True
- str.isdidig() 将消除所有包含非整数、浮点数 ('.') 和负数 ('-')(小于 2)的字符串
- int(user_input) 确认它是一个大于 2 的整数
- 如果两者都为 True,则返回 True
回答by user2788525
The problem with using the int()
built-in shown in other answers is that it will convert float and booleans to integers, so it's not really a check that your argument was an integer.
使用int()
其他答案中显示的内置函数的问题在于它会将浮点数和布尔值转换为整数,因此它并不是真正检查您的参数是否为整数。
It's tempting to use the built-in isinstance(value, int)
method on its own, but unfortunately, it will return True if passed a boolean. So here's my short and sweet Python 3.7 solution if you want stricttype checking:
单独使用内置isinstance(value, int)
方法很诱人,但不幸的是,如果传递一个布尔值,它将返回 True。所以如果你想要严格的类型检查,这是我简短而甜蜜的 Python 3.7 解决方案:
def is_integer(value):
if isinstance(value, bool):
return False
else:
return isinstance(value, int)
Results:
结果:
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
etc...
等等...