Is there a way to not convert a variable to a different type if it can't be converted?

Question:

Is there a way to not convert a variable to a different type if it can’t be converted?

For example :

    numberOneString = input("Input a number")
    
    numberOne = int(numberOne)
    
    print(numberOneString)

This gives an error when you try to run it if the input is a string that is not a number. Is there a way to stop that code from running if the variable cannot be converted to an int but run the code if it can be converted into an int?

Asked By: Crossbow4000

||

Answers:

Put the conversion inside a try/except block.

numberOne = input("Input a number")
# at this point, numberOne is a string

try:
    numberOne = int(numberOne)
    # if we get to this line, int succeeded, so numberOne is now an integer
except ValueError:
    pass

print(numberOne)
# at this point, numberOne may be an integer or a string
Answered By: John Gordon

Python tends to take the view that you should ask forgiveness, not permission. With that in mind, the error thrown is a ValueError, so the idiomatic thing to do is to attempt the conversion and handle the case where it fails.

numberOneString = input("Input a number")
try:
    numberOne = int(numberOneString)
except ValueError:
    print("That's not a real number, please try again.")
    exit(1)
print(numberOne)
Answered By: Silvio Mayolo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.