TL ; DR:
We can tell computers to perform calculations for us using
+,-,*,/:print(2 + 6) # Prints 8 print(10 - 7) # Prints 3 print(3 * 3) # Prints 9 print(6 / 2) # Prints 3
We can also use variables. In these examples, Python will replace variable
numwith its value6to do the calculations:num = 6 print(num + 5) # Prints 11 print(10 - num) # Prints 4 print(3 * num) # Prints 18 print(num / 2) # Prints 3
Full lesson:
Computers absolutely excel at performing calculations. The "compute" in their name comes from their historical association with providing answers to mathematical questions.
We've learned that in Python there are two types of numbers: integers, which are whole numbers like 10, and floating point numbers or floats, which are numbers with a decimal point like 3.145.
Arithmetic operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
| Operator | Name | Examples |
|---|---|---|
| + | Addition | 3 + 5, x + 5, 3 + y, x + y |
| - | Subtraction | 8 - 3, 8 - y, x - 3, x - y |
| * | Multiplication | 3 * 5, 3 * y, x * 5, x * y |
| / | Division | 8 / 4, 8 / y, x / 8, x / y |
| % | Modulus | 8 % 4, 8 % y, x % 4, x % y |
| ** | Exponentiation | 3 ** 2, 3 ** y, x ** 3, x ** y |
| // | Floor division | 8 // 4, 8 // y, x // 8, x // y |
Note that performing arithmetic on variables does not change the variable - you can only update a variable using the = sign.
Let's go through some examples together to better understand how each operator works:
Addition
# Declare 2 variables and initialize them:
a = 2
b = 3
print(a + b) # Output: 5
print(a + 10) # Output: 12
Subtraction
# Declare 2 variables and initialize them:
a = 2
b = 3
print(a - b) # Output: -1
print(10 - b) # Output: 7
Multiplication
# Declare 2 variables and initialize them:
a = 2
b = 3
print(a * 5) # Output: 10
print(-2 * a * b) # Output: -12
Division
# Declare 2 variables and initialize them:
a = 2
b = 3
print(b / a) # Output: 1.5
print(a / 10) # Output: 0.2
Exponentiation
The ** operator performs the exponential calculation (2**3 translates to 2 * 2 * 2):
# Declare 2 variables and initialize them:
a = 2
b = 3
print(2 ** 3) # Output: 8
print(b ** a) # Output: 9
We left the modulo (%) and floor division (//) operators for the next lesson.
Assignment
Follow the Coding Tutorial and let's practice with arithmetic operators!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
