Arithmetic Operators
Arithmetic operators are the fundamental tools for performing mathematical calculations in Python. They work on numeric types like integers (int), floating-point numbers (float), and complex numbers (complex).
The Core Arithmetic Operators
Addition +
The + operator sums two numbers. It can also be used to concatenate sequences like strings and lists.
Pyground
Calculate the total of two scores.
Expected Output:
Total score: 177
Output:
Important Nuances
Operations with Mixed Types
When you perform an arithmetic operation with an int and a float, Python automatically coerces the int to a float, and the result is always a float.
Pyground
Add an integer and a float.
Expected Output:
The result is 15.5 The type of the result is <class 'float'>
Output:
Floor Division and Modulus with Negative Numbers
Python’s behavior with negative numbers ensures that the identity a == (a // b) * b + (a % b) is always true. This means the remainder (%) will have the same sign as the divisor (b).
Pyground
Calculate floor division and modulus for -7 and 5.
Expected Output:
-7 // 5 = -2 -7 % 5 = 3
Output:
Augmented Assignment Operators
For every arithmetic operator, there’s a corresponding augmented assignment operator (e.g., +=, -=, *=). These modify the variable in-place, which can be more efficient and is often more concise.
x = x + 3 is equivalent to x += 3.
Pyground
Start with a score of 100 and apply several augmented assignments.
Expected Output:
Initial score: 100 After += 10: 110 After -= 20: 90 After *= 2: 180
Output:
For mutable types like lists, augmented assignment (+=) modifies the list in-place, while the standard operator (+) creates a new list. This is a critical distinction!