0

I am not exactly sure how to word this question so please bear with me. And I am semi-new to python. I have this very simple program using raw_input and I want to test if the user input can be converted to an int. I am aware the raw_input returns a string

while True:
    user = raw_input('?')

something to test if the user can be converted to a int, if yes then convert it, if not leave it as a string

0

1 Answer 1

1

You can use try/except and leave the except case empty (with pass):

userInput = raw_input("Give some input: ")

try:
    userInput = int(userInput)
except ValueError:
    pass
Sign up to request clarification or add additional context in comments.

3 Comments

(1) Never use a raw except if you can avoid it. Use except ValueError in this case as that is the error thrown by int. (2) Something probably should go in the except block depending on what OP wants to do next. Right now this program has the same result whatever happens, and if it tries to use userInput later it'll just throw a different kind of error when the input is invalid.
Yeah, you're right about the ValueError catching, I edited my answer. About your second point though: The OP specified: if yes then convert it, if not leave it as a string so technically there is nothing wrong about my answer. Yes, it doesn't make a lot of sense to just change the variable from string to int if possible and otherwise not, since you'll have to check for this every time you want to use the variable later on, but this is up to the OP to decide on how he wants to handle that.
Sorry, I misunderstood the code, I see now that it makes sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.