Q:

Integer Input Validation with Exception Handling (Example of ValueError Exception) in Python

belongs to collection: Python Exception Handling Programs

0

Write a Python program to read integers only by handing the ValueError Exception.

Problem Solution: In the program, we are reading an integer using int(input()) from the user and handling the expectation by using the try and expect statement.

When the user inputs a value other than an integer, the program will generate ValueError and in the program, ValueError is being handled using the "except ValueError:" block.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python program to handle ValueError expectation

while(True):

 try:
     k = int(input("Enter First Value: "))
     print("Entered value is: ",k)
     break

 except ValueError as e:
    print("Input Integer Only...",e)

Output:

Enter First Value: 12.34
Input Integer Only... invalid literal for int() with base 10: '12.34'
Enter First Value: Hello
Input Integer Only... invalid literal for int() with base 10: 'Hello'
Enter First Value: 123Hello
Input Integer Only... invalid literal for int() with base 10: '123Hello'
Enter First Value: 123
Entered value is:  123

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Add two integers only with Exception Handling in P... >>
<< Python program to illustrate the import exception ...