Python Numbers – Integers and Floats
Python Numbers
In Python, numbers are one of the most fundamental data types, and they are divided into several types. The most commonly used are:
- Integers (int) - Whole numbers without a decimal point
- Floating-point numbers (float) - Numbers with a decimal point
These numeric types are used in arithmetic operations, data calculations, loops, and much more.
1. Python Integers (int)
An integer is a whole number (positive, negative, or zero) without a decimal point.
Example:
a = 10
b = -5
c = 0
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'int'> <class 'int'> <class 'int'>
Integers can be used in mathematical operations:
x = 7
y = 3
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x // y) # Integer Division
print(x % y) # Modulo
Output:
10 4 21 2 1
2. Python Floating Point Numbers (float)
A float is a number with a decimal point or in scientific notation.
Example:
a = 10.5
b = -3.14
c = 2.0
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'float'> <class 'float'> <class 'float'>
Float Arithmetic:
x = 5.5
y = 2.0
print(x + y)
print(x - y)
print(x * y)
print(x / y)
Output:
7.5 3.5 11.0 2.75
Type Checking Using type()
You can use type() to identify the number type:
print(type(42)) # int
print(type(3.1415)) # float
Convert Between Int and Float
Python supports type conversion between integers and floats.
Example:
x = 7
y = float(x) # Convert int to float
print(y)
z = 3.99
w = int(z) # Convert float to int (truncates decimal)
print(w)
Output:
7.0 3
Using Numbers in Expressions
You can mix integers and floats in expressions. Python will automatically convert integers to floats when needed.
Example:
a = 5
b = 2.5
print(a + b)
print(type(a + b))
Output:
7.5 <class 'float'>
Scientific Notation with Floats
You can use exponential notation to represent very large or small numbers:
x = 3e2 # 3 × 10² = 300.0
y = 5e-1 # 5 × 10⁻¹ = 0.5
print(x)
print(y)
Output:
300.0 0.5
Summary of Python Number Types
Data Type | Description | Example |
---|---|---|
int | Whole numbers | 0, -3, 100 |
float | Decimal numbers | 3.14, -2.5, 0.0 |
complex | Complex numbers (optional) | 2 + 3j |