ziggy ziggy - 6 months ago 22
Python Question

Python if conversion str/int

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

Answer

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