Python Numbers: A Complete Tutorial
In Python, numbers are one of the most commonly used data types. Whether you're building a calculator, working with data, or writing game logic, you’ll need to know how numbers work.
This tutorial covers everything you need to get started with Python numbers.
Types of Numbers in Python
Python has three main types of numeric data:
Type | Description | Example |
---|---|---|
int | Integer numbers (whole numbers) | 5 , -20 , 1000 |
float | Floating point numbers (decimals) | 3.14 , -0.01 |
complex | Complex numbers (real + imaginary) | 3 + 5j , 2j |
Integers (int
)
Integers are whole numbers without a decimal point.
a = 10
b = -5
c = 0
print(type(a)) # <class 'int'>
Floating-Point Numbers (float
)
Floating-point numbers are real numbers with decimals.
x = 3.14
y = -0.001
z = 0.0
print(type(x)) # <class 'float'>
Complex Numbers (complex
)
Complex numbers have a real and imaginary part.
num = 2 + 3j
print(num.real) # 2.0
print(num.imag) # 3.0
print(type(num)) # <class 'complex'>
Basic Arithmetic Operations
Python supports common arithmetic operations:
Operator | Description | Example |
---|---|---|
+ | Addition | 2 + 3 = 5 |
- | Subtraction | 5 - 2 = 3 |
* | Multiplication | 3 * 4 = 12 |
/ | Division | 10 / 2 = 5.0 (always returns float) |
// | Floor Division | 7 // 2 = 3 |
% | Modulus (remainder) | 7 % 2 = 1 |
** | Exponentiation | 2 ** 3 = 8 |
print(10 + 5) # 15
print(10 / 3) # 3.333...
print(10 // 3) # 3
print(2 ** 4) # 16
Type Conversion
You can convert between types using int()
, float()
, and complex()
:
print(int(3.99)) # 3
print(float(5)) # 5.0
print(complex(4)) # (4+0j)
⚠️ Converting a float to an int truncates the decimal part.
Checking Number Type
Use the type()
function or isinstance()
:
a = 10
print(type(a)) # <class 'int'>
print(isinstance(a, int)) # True
Useful Math Functions
Python has built-in and library-supported math functions:
Built-in:
abs(-7) # 7
round(3.1416, 2) # 3.14
pow(2, 3) # 8
math
module:
import math
math.sqrt(16) # 4.0
math.ceil(4.2) # 5
math.floor(4.7) # 4
math.pi # 3.14159...
Comparisons and Boolean Logic
You can compare numbers using:
Operator | Meaning |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
a = 5
b = 7
print(a < b) # True
✅ Summary
- Python has three main number types:
int
,float
,complex
- Supports full arithmetic operations
- You can convert between number types
- Use
math
module for advanced operations