Python Addition Operator

Python provides the addition operator + to add two objects. The semantics of the addition depends on the operands’ data types. For example, adding two integers perform arithmetic addition whereas adding two lists performs list concatenation. The specific return value of the addition operator is defined in a data types’ __add__() magic method.

Have a look at the following examples!

Examples

The + operator on integer operands yields another integer—the mathematical sum of both operands:

>>> 2 + 2
4
>>> 2 + 3
5
>>> -99 + (-1)
-100

If at least one of the operands is a float value, the result is also a float—float is infectious!

>>> 2.0 + 1
3.0
>>> 1 + 2.2
3.2
>>> 2.0 + 40.0
42.0

Can we add strings? Of course! The result is a new string from gluing the second string to the first. This is called string concatenation:

>>> 'learn' + ' python'
'learn python'
>>> 'fi' + 'nxter'
'finxter'

If the operands are lists, the result of the addition operation is another list. It creates a new list with the elements of the first list plus the elements of the second list. The original lists remain unchanged.

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> l1 = ['alice']
>>> l2 = ['ann', 'bob']
>>> l1 + l2
['alice', 'ann', 'bob']
>>> l1
['alice']
>>> l2
['ann', 'bob']
>>> 

What if two operands have an incompatible data type—unlike floats and integers? For example, if you try to add a string to a list?

>>> 'hello' + ['world']
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    'hello' + ['world']
TypeError: can only concatenate str (not "list") to str

The result of incompatible addition is a TypeError. You can fix it by using only compatible data types for the addition operation.

Can you use the addition operator on custom objects? Yes!

Python Addition Magic Method

To use the addition operator on custom objects, you need to define the __add__() dunder method that takes two arguments: self and other and returns the result of self + other. To obtain the result for a custom object, you can use the attributes (data) maintained in this object.

In the following code, you add two baskets together by combining their contents:

class Basket:
    def __init__(self, contents):
        self.contents = contents

    def __add__(self, other):
        return Basket(self.contents + other.contents)

my_basket = Basket(['banana', 'apple', 'juice'])
your_basket = Basket(['bred', 'butter'])

our_basket = my_basket + your_basket
print(our_basket.contents)

The output of this code snippet is the combined basket:

['banana', 'apple', 'juice', 'bred', 'butter']

The code consists of the following steps:

  • Create the class Basket that holds the list contents to store some goods.
  • Define the magic method __add__ that creates a new Basket by combining the list of goods (contents) from the two operand baskets. Note that we rely on the already implemented addition operator on lists, i.e., list concatenation, to actually implement the addition operator for baskets.
  • We create two baskets my_basket and your_basket, and add them together to a new basket our_basket using the defined addition operation.

Python Addition Program with User Input

To create a simple addition program in Python taking the user’s input and adding together the provided numbers, you can use the following four steps:

  1. Get the user input as a string using the built-in input() function, and store the result in variables num_1 and num_2.
  2. Convert the string user inputs to numerical types using, for example, the int() or float() constructors.
  3. Add together the numerical values using the addition operator num_1 + num_2.
  4. Print the result to the Python shell.

Here are those four steps in Python code:

# Python addition program with user input

# 1. Get string user inputs representing integers
num_1 = input('First number: ')
num_2 = input('Second number: ')

# 2. Converting strings to ints
num_1 = int(num_1)
num_2 = int(num_2)

# 3. Adding numbers
result = num_1 + num_2

# 4. Display the result
print(num_1, '+', num_2, '=', result)

Here’s an example code execution where I put in integers 40 and 2 and calculated the sum of both using the addition operator:

First number: 40
Second number: 2
40 + 2 = 42

Python Addition Operator Chaining

You can chain together two addition operators. For example, the expression x + y + z would first add together x and y and then add z to the resulting object. Thus, it is semantically identical to ((x + y) + z).

Here’s a minimal example:

>>> x = 10
>>> y = 5
>>> z = 2
>>> x + y + z
17
>>> ((x + y) + z)
17

Comparison Operators

Comparison operators are applied to comparable objects and they return a Boolean value (True or False).

OperatorNameDescriptionExample
>Greater ThanReturns True if the left operand is greater than the right operand3 > 2 == True
<Less ThanReturns True if the left operand is smaller than the right operand3 < 2 == False
==Equal ToReturns True if the left operand is the same as the right operand(3 == 2) == False
!=Not Equal ToReturns True if the left operand is not the same as the right operand(3 != 2) == True
>=Greater Than or Equal ToReturns True if the left operand is greater than or equal to the right operand(3 >= 3) == True
<=Less Than or Equal ToReturns True if the left operand is less than or equal to the right operand(3 <= 2) == False