There are two types of numbers you'll see frequently in Python: integers and floating point numbers.
Integers
Integers are used for representing whole numbers.
>>> 5
5
>>> 0
0
>>> 999999999999
999999999999
>>> -10
-10
Any number that doesn't have a decimal point in it is an integer.
Floating point numbers
Floating point numbers are used for representing non-integers.
>>> 2.5
2.5
>>> 3.14159265358979
3.14159265358979
Mixing integers and floating point numbers
Integers and floating point numbers can work together.
So we can add, subtract, multiply, and divide these two types of numbers and we'll get the results we'd expect to get:
>>> 3.5 + 4
7.5
>>> 8 - 2.2
5.8
>>> 6.5 * 4
26.0
>>> 8.4 / 2
4.2
Whenever we mix integers and floating point numbers, we'll get a floating point number back.
For most operations we might perform between two integers, we'll get an integer back:
>>> 5 + 2
7
>>> 5 - 6
-1
>>> 5 * 3
15
But if we divide two integers, we'll always get a floating point number back:
>>> 5 / 2
2.5
>>> 6 / 3
2.0
That's because not all division between two integers has an integer answer.
You'll see both integers and floating point numbers quite often in Python.
Arithmetic operations
Python supports addition, subtraction, multiplication and division.
It also has an integer division operator that will return how many times one whole number fully divides into another:
>>> 26 // 7
3
And there's a modulo operator for finding the remainder from an integer division operation:
>>> 26 % 7
5
We get 5 here because 3 times 7 plus 5 is 26:
>>> 3 * 7 + 5
26
Python also has an operator for exponential operations.
This is 2 raised to the 10-th power:
>>> 2 ** 10
1024
Operator precedence in Python
Python follows the PEMDAS rule. Operations are performed in this order:
- P: Parentheses
- E: Exponents
- MD: Multiplication and Division
- AS: Addition and Subtraction
And operations of the same type are performed from left to right.
So the multiplication is performed before the addition here:
>>> 2 + 3 * 4
14
We can specify the order of operations explicitly by using parentheses for grouping:
>>> (2 + 3) * 4
20
Multiple levels of parentheses also work:
>>> 2 * (3 + 4 * (5 + 2))
62
Arithmetic in Python is similar to in math
Common arithmetic operations work pretty much the way you might expect them to.
New to Python? Try Python Jumpstart!
Python Jumpstart is designed to help new Python programmers get up to speed quickly. Get hands-on practice with 50 bite-sized modules that build your Python skills step by step.
Python's // operator performs "floor division" (a.k.a. "integer division"). It always rounds down the result to the nearest integer while dividing.