×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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 »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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