Arithmetic operations in Python ( + – * / // % ** )
In this lesson we will learn how Python works with numbers and which arithmetic operators we can use. These operations are basic and we will use them in almost every program.
Basic arithmetic operators
Python supports the following basic operations:
- Addition —
a + b - Subtraction —
a - b - Multiplication —
a * b - Division (decimal) —
a / b
print(5 + 3) # 8
print(10 - 4) # 6
print(6 * 7) # 42
print(15 / 2) # 7.5
Integer division — //
The operator // returns the result of division without the decimal part — only a whole number.
print(15 // 2) # 7
print(20 // 3) # 6
print(10 // 5) # 2
Note: It always rounds down.
Modulo — the remainder of division (%)
The operator % gives the remainder when one number is divided by another.
print(10 % 3) # 1
print(15 % 4) # 3
print(18 % 2) # 0 # an even number
This is very useful for checking whether a number is even:
print(7 % 2) # 1 means odd
print(8 % 2) # 0 means even
Exponentiation — **
The operator ** is used to raise numbers to a power.
print(2 ** 3) # 8
print(5 ** 2) # 25
print(10 ** 0) # 1
Combining operations
We can combine several operations in one line:
print(2 + 3 * 4) # what do you think the result is?
print((2 + 3) * 4) # brackets change the order
Operator precedence — the order of calculation
Python calculates operations in a certain order, just like in mathematics:
- 1. exponentiation —
** - 2. multiplication, division, modulo —
*///% - 3. addition and subtraction —
+-
Brackets always come first, and you can use them to change the order of calculation.
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
print(2 ** 3 * 2) # 16
print(2 ** (3 * 2)) # 64
Short tasks
- Calculate the sum of the numbers 125 and 378.
- Write a program that calculates how many whole times the number 7 fits into the number 50 (using
//). - Make a program that checks whether a number (of your choice) is even or odd (use
%). - Calculate the area of a square if its side is 12 (formula: a * a).
- How many seconds are there in 5 hours? (use several operations)
Possible solutions
print(125 + 378)
print(50 // 7)
number = 13
print(number % 2)
a = 12
print(a * a)
print(5 * 60 * 60)
Mini project — a simple calculator
In the next lesson we will use input(), but for now here is a version with values given in advance:
a = 12
b = 4
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)
In the next lesson we make a real calculator that works with user input.
Hidden mini quiz
Click to check your knowledge!
Open the quiz
Mini quiz: Arithmetic operations in Python
1. What does the operator // do in Python?
2. What is the result of the expression 10 % 4?
3. Which operator is used for exponentiation in Python?
4. Which operator has higher priority (precedence) in the expression?
2 + 3 * 45. What will the following code print?
print(2 ** 3 * 2)