Python Practice › Exception Handling Programs › Program 2
Handle invalid integer input
Write a Python program that converts text to an integer and reports invalid values.
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
int()raisesValueErrorfor text that is not a whole number.
Solution
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.