Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Python-验证用户输入_String_Python 3.x_Validation_Int - Fatal编程技术网

String Python-验证用户输入

String Python-验证用户输入,string,python-3.x,validation,int,String,Python 3.x,Validation,Int,我的代码需要验证用户输入,以确保他们输入一个数字,并保持循环,直到他们输入一个数字 我的代码: user_input=input("Enter a number: ") while user_input != int: user_input=input("Error: Enter a number: ") 我的输出: 输入一个数字:d 错误:输入一个数字:f 错误:输入一个数字:5 错误:输入一个数字:5 错误:输入一个数字:3 为什么它甚至不接受数字 回答 我认为下面的代码以一种容易

我的代码需要验证用户输入,以确保他们输入一个数字,并保持循环,直到他们输入一个数字

我的代码:

user_input=input("Enter a number: ")
while user_input != int:
    user_input=input("Error: Enter a number: ")
我的输出:

输入一个数字:d

错误:输入一个数字:f

错误:输入一个数字:5

错误:输入一个数字:5

错误:输入一个数字:3


为什么它甚至不接受数字

回答

我认为下面的代码以一种容易理解的方式解决了您的问题

user_input = input("Enter a number: ")
while not user_input.isnumeric():
    user_input = input("Error: Enter a number: ")
解释

由于用户输入时出现
,您的代码无法运行!=int

>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
>>> int(num)
5
>>> isinstance(num, int)
True
当您调用
input
函数并由用户提供输入时,该输入始终是字符串

>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
您的目的是检查
num
是否是一个数字。因此,要检查字符串是否表示某个数字,可以使用
str.isdigit()
str.isdecimal()
str.isnumeric()
方法。你可以读更多

人们很容易错误地认为下面的方法是可行的,但它很快就会变得混乱

while not isinstance(user_input, int):
请记住,调用
input
函数后收到的输入将是一个字符串。因此,上面的代码总是正确的,这不是您想要的。但是,如果将
用户输入
更改为
int
类型,则上述代码可以工作

>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
>>> int(num)
5
>>> isinstance(num, int)
True
但是,如果
num
是其他内容,那么解释器将抛出一个错误

>>> num = input('Enter a number: ') # 'A'
>>> int(num)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'A'
>>num=input('输入一个数字:')#'a'
>>>整数(num)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:基数为10的int()的文本无效:“A”
这让我们回到了答案,它涉及到使用string方法检查字符串是否代表某个数字。我选择使用
str.isnumeric()
方法,因为它是最灵活的


我希望这能回答你的问题。快乐编码

您所需要的可能就是
user\u input.isnumeric()