w3resource

Python: Add two objects if both objects are an integer type

Python Basic: Exercise-36 with Solution

Write a Python program to add two objects if both objects are integers.

Sample Solution:

Python Code:

# Define a function 'add_numbers' that takes two arguments: a and b.
def add_numbers(a, b):
    # Check if both 'a' and 'b' are integers using the 'isinstance' function.
    if not (isinstance(a, int) and isinstance(b, int)):
        # If either 'a' or 'b' is not an integer, return an error message.
        return "Inputs must be integers!"
    # If both 'a' and 'b' are integers, return their sum.
    return a + b

# Test the 'add_numbers' function with various input values and print the results.
print(add_numbers(10, 20))     # Valid: Both inputs are integers, and it returns the sum.
print(add_numbers(10, 20.23))  # Invalid: One of the inputs is a float, so it returns an error message.
print(add_numbers('5', 6))     # Invalid: One of the inputs is a string, so it returns an error message.
print(add_numbers('5', '6'))   # Invalid: Both inputs are strings, so it returns an error message.

Sample Output:

30
Inputs must be integers!
Inputs must be integers!
Inputs must be integers!

Explanation:

The said code defines a function called "add_numbers(a, b)" that takes two integers "a" and "b" as arguments. The function first checks if "a" and "b" are both instances of the "int" data type using the "isinstance" function. If either "a" or "b" is not an integer, the function returns the string "Inputs must be integers!"

Finally the code calls the function four times with different arguments, passing i) two integers, ii) an integer and a float, iii) a string and an integer and iv) two strings.

It will return the sum of the integers passed in the first call. For the second, third and fourth calls will return the string "Inputs must be integers!" as the inputs passed are not integers.

Flowchart:

Flowchart: Add two objects if both objects are an integer type.

Python Code Editor:

 

Previous: Write a Python program which will return true if the two given integer values are equal or their sum or difference is 5.
Next: Write a Python program to display your details like name, age, address in three different lines.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.