Python - 用户输入数据类型

时间:2016-04-06 13:06:58

标签: python python-3.x

我在Python 3.x中编写了以下代码来验证用户的输入:

while True:
    try:
        answer = int(input("Enter an integer: "))
    except ValueError:
        print("That's not a whole number. Try again.")

我知道输入'hi'或'hi46'会是字符串(会导致ValueError)。

输入什么数据类型''(什么都没有)?输入']%$'(符号)怎么样?

3 个答案:

答案 0 :(得分:1)

假设您正在使用python 3.X,所有,用户输入将是一个字符串。甚至数字看上去像“23”或“0”。 int(thing)不验证thing是否为整数类型。它试图将thing从现在的任何类型转换为整数类型,如果不可能则引发ValueError。

演示:

>>> while True:
...     x = input("Enter something: ")
...     print("You entered {}".format(x))
...     print("That object's type is: {}".format(type(x)))
...
Enter something: hi
You entered hi
That object's type is: <class 'str'>
Enter something: hi46
You entered hi46
That object's type is: <class 'str'>
Enter something: 
You entered
That object's type is: <class 'str'>
Enter something: ]%$
You entered ]%$
That object's type is: <class 'str'>
Enter something: 23
You entered 23
That object's type is: <class 'str'>
Enter something: 42
You entered 42
That object's type is: <class 'str'>
Enter something: 0
You entered 0
That object's type is: <class 'str'>

答案 1 :(得分:0)

字符串,您input()的所有内容都是字符串。除了C-c int()如果Query query = pm.newQuery(Register.class); query.setFilter("email== eemail"); query.declareParameters("string eemail"); return (Member)query.execute(email); 提出它,所有这些都会引起价值误差。

答案 2 :(得分:0)

您可以在不依赖于使用isdigit()的情况下执行此操作:

answer = input("Enter an integer: ")
while not answer.isdigit():
    print("That's not a whole number. Try again.")
    answer = input("Enter an integer: ")
answer = int(answer)

isdigit()测试输入字符串是否完全由可以用int()转换的数字组成。