0

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?

2 Answers2

1

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)
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

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
John Gordon
  • 29,573
  • 7
  • 33
  • 58