0

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.

2
  • Please don't use object as a variable name; it's a builtin name used to refer to the Python universal base class. (Plus, it's a terribly generic name to start with.) Commented Jan 28, 2013 at 22:36
  • It has a unique name in my actual code, but I wanted to simplify my question. Still, thanks for your feedback/insight! Commented Jan 28, 2013 at 22:50

2 Answers 2

2
while True:
 try:
  object = int(input("Please enter an integer"))
  break
 except ValueError:
  print("Invalid input.  Please try again")
print(type(object))
print(object)
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thanks for prodding me to read more carefully, t'is indeed a ValueError. No such thing as a traceback error! Whoops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.