While testing your last challenge did you enter something that wasn’t an integer to see what would happen?
![An error message from trying to force a string into an integer that wouldn't work](https://blogs.glowscotland.org.uk/es/public/software/uploads/sites/4063/2023/02/14133109/error2-1.png)
This happened because using the int function to force something into an integer only works if it can be an integer. “10” can become 10, but “Hello world” cannot become an integer. How to fix this?
Try…except
To get around this we can use the try…except keywords. They basically say “Try this code, but if you get an exception then do this instead”. So it will try the code indented under the try keyword and if everything goes well then it skips the except code. But if an error is raised then you can run the except block.
The except block can match different or multiple exception types. For now we’ll just use the ValueError as that is what the error message above showed we would get when trying to convert that string.
while True:
try:
input_number = int(input("Please enter a number: "))
break
except ValueError:
print("That isn't a valid number")
print("Thank you for entering " + str(input_number))
Notice how in the print line we use str to convert the integer back to a string for concatenation.
This is only touching the surface of the try and except features. But it is enough for us to fix this problem.
For more information you can look at the documentation about it if you are having difficulty getting to sleep.
Mini challenge
Go back and alter your last challenge code to use try and except so that it can now handle a user typing in something that isn’t an integer.