python3-input()的数据类型 [英] python3 - data type of input()
问题描述
我需要将一个用户提供的整数值分配给一个对象.我的格式如下:
I need to assign a user-provided integer value to an object. My format is as follows:
object = input("Please enter an integer")
以下打印测试...
print(type(object))
print(object)
...返回< class'str'>
和'1'.有没有一种方法可以将对象"的数据类型设置为用户输入值的数据类型?IOW,如果object = 1,则type(object)= int?我知道我可以使用以下命令将输入的数据类型设置为int:
...return <class 'str'>
and '1'. Is there a way to set the data type of 'object' to the data type of the user's input value? IOW, such that if object=1, type(object)=int? I know I can set the data type of an input to int using the following:
object = int(input("Please enter an integer"))
在这种情况下,如果用户不提供int,则控制台将引发回溯错误,并且程序将崩溃.我更愿意测试对象是否实际上是一个int值.如果不是,请使用我的程序打印一条错误语句并递归抛出前一个提示.
In this case, if the user does not provide an int, the console throws a traceback error and the program crashes. I would prefer to test whether the object is in fact an int; if not, use my program to print an error statement and recursively throw the previous prompt.
推荐答案
while True:
try:
object = int(input("Please enter an integer"))
break
except ValueError:
print("Invalid input. Please try again")
print(type(object))
print(object)
这篇关于python3-input()的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!