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

Here, we are going to learn how to input only integer number in Python? We are writing a Python program to input an integer and handling ValueError exception.
Submitted by IncludeHelp, on February 18, 2021

Problem Statement: 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.

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

Python exception handling programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.