Numbers and Arithmetic Operations¶
Python supports integers, floating-point numbers, and complex numbers out of the box.
Numeric Types in Python¶
- Integer (
int): Whole numbers without decimals. Python integers have unlimited precision. - Floating-point (
float): Numbers containing a decimal point, implemented using IEEE 754 double precision. - Complex (
complex): Numbers written in the form $a + bj$, where $j$ is the imaginary unit.
Example: Numeric Types
x = 10 # int
pi = 3.14159 # float
z = 2 + 5j # complex
print(type(x))
print(type(pi))
print(type(z))
Output
<class 'int'> <class 'float'> <class 'complex'>
Arithmetic Operators¶
| Operator | Operation | Syntax | Example | Result |
|---|---|---|---|---|
+ | Addition | a + b | 10 + 5 | 15 |
- | Subtraction | a - b | 10 - 3 | 7 |
* | Multiplication | a * b | 4 * 3 | 12 |
/ | True Division | a / b | 7 / 2 | 3.5 (always float) |
// | Floor Division | a // b | 7 // 2 | 3 (discards fractional part) |
% | Modulo | a % b | 7 % 2 | 1 (remainder) |
** | Exponentiation | a ** b | 2 ** 3 | 8 |
Division: True Division vs Floor Division¶
- True division (
/) always returns a floating-point number, even if the division divides evenly. - Floor division (
//) rounds down to the nearest integer.
Example: Division Comparison
Exponentiation and Large Numbers¶
Use ** to calculate powers:
Example: Powers and Large Integers
In Python 3, integers automatically handle arbitrarily large numbers without buffer overflow.
Underscores in Numeric Literals¶
To improve readability of large numbers, underscores can be placed between digits:
Augmented Assignment Operators¶
Operators can be combined with = to modify a variable in-place: