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

ziggy
  • 1,488
  • 5
  • 23
  • 51

1 Answers1

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
Keiwan
  • 8,031
  • 5
  • 36
  • 49
  • (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. – Alex Hall May 20 '16 at 19:08
  • 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. – Keiwan May 20 '16 at 19:15
  • Sorry, I misunderstood the code, I see now that it makes sense. – Alex Hall May 20 '16 at 19:16