Handle invalid integer input

EasyException Handling Programs · 2 of 20

Write a Python program that converts text to an integer and reports invalid values.

Advertisement
Input
"42", "4.2", "abc"
Output
42 -> 42
4.2 -> invalid: invalid literal for int() with base 10: '4.2'
abc -> invalid: invalid literal for int() with base 10: 'abc'

Approach

  1. int() raises ValueError for text that is not a whole number.

Solution

Python
for text in ["42", "4.2", "abc"]:    try:        print(text, "->", int(text))    except ValueError as e:        print(text, "-> invalid:", e)
Output
42 -> 42
4.2 -> invalid: invalid literal for int() with base 10: '4.2'
abc -> invalid: invalid literal for int() with base 10: 'abc'

Line by line

Line 4

as e gives access to the message Python created.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment