Python Number Types
Number types are used to store numeric values. They are immutable data types, which means changing the value of a numeric variable actually creates a new object.
Python supports three main numeric types:
- Integer (
int): Positive or negative integers without decimal points. Integers in Python 3 can be arbitrarily large, limited only by memory. - Float (
float): Positive or negative real numbers with decimal points. Can also be represented in scientific notation (e.g.,2.5e2represents 2.5 * 10^2 = 250). - Complex (
complex): Composed of a real part and an imaginary part, in the forma + bj, wherejis the imaginary unit.
python
# Integers
x = 10
y = -3000
z = 12345678901234567890
# Floats
pi = 3.14
price = -19.99
scientific = 1.23E4 # 1.23 * 10^4 = 12300.0
# Complex numbers
c = 1 + 2jBasic Arithmetic Operations
Python supports all standard arithmetic operators.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 5 / 2 | 2.5 |
// | Floor Division | 5 // 2 | 2 |
% | Modulo | 5 % 2 | 1 |
** | Exponentiation | 5 ** 2 | 25 |
Example:
python
a = 10
b = 3
print(f"a + b = {a + b}")
print(f"a / b = {a / b}")
print(f"a // b = {a // b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")Type Conversion in Operations
When an expression contains both integers and floats, Python automatically converts integers to floats to maintain precision. This conversion is implicit.
python
result = 3 + 4.5
print(result) # Output: 7.5
print(type(result)) # Output: <class 'float'>Number Type Conversion Functions
You can also use built-in functions to explicitly convert between different number types.
int(x): Convertsxto an integer (truncates the decimal).float(x): Convertsxto a float.complex(x): Convertsxto a complex number with real partxand imaginary part 0.complex(x, y): Creates a complex number with real partxand imaginary party.
python
print(int(9.9)) # Output: 9
print(float(10)) # Output: 10.0
print(complex(5)) # Output: (5+0j)
print(complex(2, -3)) # Output: (2-3j)Math Module math
For more advanced mathematical operations like trigonometric functions, logarithms, square roots, etc., you need to import the math module.
python
import math
# Pi
print(math.pi) # Output: 3.141592653589793
# Square root
print(math.sqrt(16)) # Output: 4.0
# Round up
print(math.ceil(4.2)) # Output: 5
# Round down
print(math.floor(4.8)) # Output: 4
# Sine function
print(math.sin(math.pi / 2)) # Output: 1.0