gpt4 book ai didi

Python - 用户输入数据类型

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:32 25 4
gpt4 key购买 nike

我用 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)。

输入“”(无)会是什么数据类型?输入“]%$”(符号)怎么样?

最佳答案

假设您使用的是 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'>

关于Python - 用户输入数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com