Home »
Python »
Python programs
Add two integers only with Exception Handling in Python
Here, we are going to learn how to input and add two integers only in Python? We are writing a Python program to handle the exceptions if numbers are other than integers.
Submitted by IncludeHelp, on February 18, 2021
Problem Statement: Write a Python program input and add two integers only and handle the exceptions.
Problem Solution: In this program, we are reading two integers number from the user using int(input()) and handling the following exceptions,
- ValueError – Occurs when input value is not an integer.
- ZeroDivisionError – Occurs when divisor is zero.
- Exception – Any other error.
Python program to add two integers with handling expectations
try:
k=int(input("Enter First Value: "))
j=int(input("Enter Second Value: "))
d=k/j
print(d)
except ValueError as e:
print('Pls Input Integer Only',e)
except ZeroDivisionError as e:
print('Second Number Should Not Be Zero',e)
except Exception as e:
print('Other Error',e)
Output:
RUN 1:
Enter First Value: 10
Enter Second Value: 20
0.5
RUN 2:
Enter First Value: 10
Enter Second Value: Hello
Pls Input Integer Only invalid literal for int() with base 10: 'Hello'
RUN 3:
Enter First Value: 10
Enter Second Value: 0
Second Number Should Not Be Zero division by zero
Python exception handling programs »
TOP Interview Coding Problems/Challenges