Try/Except- Prevent from crashing program if user input is no integer - Python

 When need to ask user for entering the number int(input()) is used however user can enter no integer and program usually crashes with error: ValueError: invalid literal for int() with base 10.
There's a way to prevent from that error.

How to prevent: ValueError: invalid literal for int()

To prevent program from crash because of invalid input you can use try/except block to catch exception.


When user enters no integer in your int(input()) you can catch it with error and ask to enter number again with try/except block in while loop.


Example 1:

Enter a number: g
Try again. You can enter numbers only.
Enter a number: q
Try again. You can enter numbers only.
Enter a number: d
Try again. You can enter numbers only.
Enter a number: 2
4

Process finished with exit code 0
In line 1 infinite while loop is created then in block "try" and "except" user is asked to enter integer and if he does, loop stops by "break"statement  in line 5.
When user enters no integer, for example enters a letter character or accidentally presses Enter, "Try" and "Except Value Error" in line 6 catches this exception and prints the error, loop while starts again till the user enters integer.

 Example 2:>
Enter the number: two
Try again. You can enter numbers only
Enter the number: three
Try again. You can enter numbers only
Enter the number: 2
You choose 2

 Line 1: Asking user for input

Line2 : While loop is created with condition: loop till user variable option is a digit number. Notice user is not asked for an integer however is asked to enter a number and that value will be stored as string type. When user enters letter option.isdigit() == False when it will be a number option.isdigit() == True.
Line 3 starts a try block which tries to do something, in this case to get input as a digit.
Line 4 is asking user for input: option = input('Enter the number').
Line 5 has a Except ValueError which is catching exception if user enters no number but presses enter or enters a letter, if he does then is printed and Error and ask the user for input again.

Try and Except
are very useful in Python programming when integer is needed for mathematical operations, menu options or indexing.
 

Read also:



Comments