python3 - data type of input()

本秂侑毒 提交于 2021-01-29 18:14:30

问题


I need to assign a user-provided integer value to an object. My format is as follows:

object = input("Please enter an integer")

The following print tests...

print(type(object))
print(object)

...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"))

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.


回答1:


while True:
 try:
  object = int(input("Please enter an integer"))
  break
 except ValueError:
  print("Invalid input.  Please try again")
print(type(object))
print(object)



回答2:


You can always catch a "traceback error" and substitute your own error handling.

user_input = input("Please enter an integer")
try:
    user_number = int(user_input)
except ValueError:
    print("You didn't enter an integer!")


来源:https://stackoverflow.com/questions/14572483/python3-data-type-of-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!