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!
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:
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
Basketthat 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
your_basket, and add them together to a new basket
our_basketusing 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:
- Get the user input as a string using the built-in
input()function, and store the result in variables
- Convert the string user inputs to numerical types using, for example, the
- Add together the numerical values using the addition operator
num_1 + num_2.
- 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
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
Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.
|+||Addition||Calculating the sum of the two operands|
|–||Subtraction||Subtracting the second operand from the first operand|
|*||Multiplication||Multiplying the first with the second operand|
|/||Division||Dividing the first by the second operand|
|%||Modulo||Calculating the remainder when dividing the first by the second operand|
|//||Integer Division, Floor Division||Dividing the first operand by the second operand and rounding the result down to the next integer|
|**||Exponent||Raising the first operand to the power of the second operand|
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.