Python program to add two numbers

Generally, most of the new programming languages use the addition (+) operator to add any two values. So does python.

In the simplest form, we can directly add two numbers using the python command line as shown below.

Python 2.7.10 (default, Jul 15 2017, 17:16:57) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + 5

Here python adds two numbers and prints their sum as shown above. Let us see a few other ways to add two numbers.

Adding two numbers and passing them directly to the print function.

# add two numbers 10 and 5 and print the result.
print(10 + 5)  # prints 15 as output.

We also can add two numbers using a function. We can call the same function to get the addition of two given numbers.

# function to add two numbers.
def add(one, two):
    return one + two

# add 5 and 10 and print the result.
print(add(5, 10))

# Output

Above ‘’ prints the result of the addition of both numbers.

Addition of two floating-point numbers

In a similar way, we can use the below code to add two floating numbers which give us the resultant floating values sum.

# add two floating numbers and print.
print(4.5 + 5.5) # prints 10.0

The above code adds both the values and results in the floating-point value.

We also can add two strings and boolean values

Addition (+) operator on string object overloads as concatenation. Let us check this with an example as shown below.

# add two strings and print.
print('Hello' + ' World!')  # prints 'Hello World!'.

The above function concatenates ‘Hello’ and ‘ World!’ as one string and results in ‘Hello World!’.

The boolean values in python are like 1 or 0 for True and False values. When we try to add up these two boolean values it results in us value of 1. Below is the code to try this out in python.

# add two boolean values and print.
print(True + False) # prints '1'.

Above are some sample additions of different number types and other string and boolean types in python.

Hope this helps you to understand the addition operator on different types of values. Happy Learning!.