When we need to ask the user to enter a number, we use int(input()). However, if the user enters a non-integer value, the program will usually crash with the error: ValueError: invalid literal for int() with base 10.
There is a way to prevent this 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.
int(input()), you can catch the error and ask them to enter a number again using a try/except block inside a 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
while loop is created. Inside the try/except block, the user is asked to enter an integer. If they do, the loop stops with the break statement in line 5.If the user enters a non-integer — for example, a letter or just presses Enter — the
ValueError in the except block (line 6) catches the exception and prints an error message. The while loop then starts again, repeating until the user enters a valid 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
Line 2: A while loop is created with the condition to continue until the option variable contains a digit. Notice that the user is not explicitly asked for an integer; they are asked to enter a number, which is stored as a string. If the user enters a letter, option.isdigit() returns False; if they enter a number, it returns True.
Line 3: A try block begins, which attempts to execute code that might raise an exception — in this case, converting input to a digit.
Line 4: The user is prompted for input with option = input('Enter the number').
Line 5: The except ValueError block catches exceptions if the user presses Enter without entering anything, or enters a letter instead of a number. If an exception occurs, an error message is printed, and the user is prompted again.
try and except are very useful in Python when an integer is needed for mathematical operations, menu choices, or indexing.Read also:
- How to check if user user input is Empty
- Prevent fro crashing program when user enters no integer
- User Enters no integer - how to prevent program from crashing.

Comments
Post a Comment