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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.