Numbers in Python
Numbers are fundamental data types in Python, used for mathematical calculations, counting, measuring, and data analysis. Python provides several types of numbers with powerful built-in operations and functions that make mathematical programming intuitive and efficient.
Number Types in Python
Python 3.x supports three main types of numbers, each designed for specific use cases and mathematical operations.
- int (Integer): Whole numbers without decimal points
- float (Floating Point): Numbers with decimal points
- complex (Complex): Numbers with real and imaginary parts
Integers
Unlike many programming languages, Python 3.x integers can be infinitely large, limited only by your computer's memory. This eliminates integer overflow errors common in other languages.
# Integer examples
age = 25
temperature = -10
population = 7800000000
huge_number = 123456789012345678901234567890
# Check the type
print(type(age)) # <class 'int'>
print(type(huge_number)) # <class 'int'>
# Integer operations
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a // b) # Floor division: 3
print(a % b) # Modulus (remainder): 1
print(a ** b) # Exponentiation: 1000Floating Point Numbers
Floats are essential for scientific calculations, measurements, and any scenario requiring fractional precision. They can represent very large and very small numbers using scientific notation.
# Float examples
price = 19.99
pi = 3.14159
scientific = 1.5e6 # 1.5 × 10^6 = 1,500,000
tiny = 2.5e-4 # 2.5 × 10^-4 = 0.00025
print(type(price)) # <class 'float'>
print(scientific) # 1500000.0
print(tiny) # 0.00025
# Float operations
x = 7.5
y = 2.0
print(x / y) # Division: 3.75
print(x // y) # Floor division: 3.0
print(x ** 0.5) # Square root: 2.7386127875258306
# Precision considerations
print(0.1 + 0.2) # 0.30000000000000004 (floating point precision)
print(round(0.1 + 0.2, 1)) # 0.3 (rounded)The seemingly strange result of 0.1 + 0.2 = 0.30000000000000004 is not a Python bug! It's how computers represent decimal numbers in binary. Most decimal fractions cannot be represented exactly in binary, just like 1/3 cannot be represented exactly in decimal (0.333...).
Complex Numbers
Complex numbers are used in advanced mathematics, engineering, and scientific computing. Python has built-in support for complex number arithmetic.
# Complex number examples
z1 = 3 + 4j # 3 is real part, 4 is imaginary part
z2 = complex(2, 5) # Alternative way: real=2, imaginary=5
z3 = 1j # Pure imaginary number
print(type(z1)) # <class 'complex'>
print(z1.real) # 3.0 (real part)
print(z1.imag) # 4.0 (imaginary part)
# Complex arithmetic
result = z1 + z2 # (3+4j) + (2+5j) = (5+9j)
print(result) # (5+9j)
# Useful complex functions
print(abs(z1)) # Magnitude: 5.0
print(z1.conjugate()) # Complex conjugate: (3-4j)
# Converting between types
magnitude = abs(z1) # Returns float
print(type(magnitude)) # <class 'float'>Mathematical Operations
Python provides comprehensive mathematical operators that work seamlessly across different number types, with automatic type promotion when needed.
# Basic arithmetic operators
a = 15
b = 4
print(f"Addition: {a} + {b} = {a + b}") # 19
print(f"Subtraction: {a} - {b} = {a - b}") # 11
print(f"Multiplication: {a} * {b} = {a * b}") # 60
print(f"Division: {a} / {b} = {a / b}") # 3.75
print(f"Floor Division: {a} // {b} = {a // b}") # 3
print(f"Modulus: {a} % {b} = {a % b}") # 3
print(f"Exponentiation: {a} ** {b} = {a ** b}") # 50625
# Assignment operators (Python 3.8+)
x = 10
x += 5 # x = x + 5, now x = 15
x -= 3 # x = x - 3, now x = 12
x *= 2 # x = x * 2, now x = 24
x /= 4 # x = x / 4, now x = 6.0
x //= 2 # x = x // 2, now x = 3.0
x %= 2 # x = x % 2, now x = 1.0
x **= 3 # x = x ** 3, now x = 1.0
print(f"Final value: {x}") # 1.0Built-in Number Functions
Python provides many built-in functions for working with numbers, making mathematical operations simple and efficient.
# Essential number functions
numbers = [-5, 3.7, -2.1, 8, 0]
print(f"Absolute value: abs(-5) = {abs(-5)}") # 5
print(f"Minimum: min(numbers) = {min(numbers)}") # -5
print(f"Maximum: max(numbers) = {max(numbers)}") # 8
print(f"Sum: sum(numbers) = {sum(numbers)}") # 4.6
print(f"Length: len(numbers) = {len(numbers)}") # 5
# Rounding functions
value = 3.7826
print(f"Round to 2 decimals: round({value}, 2) = {round(value, 2)}") # 3.78
print(f"Round to nearest int: round({value}) = {round(value)}") # 4
# Power and square root
import math
print(f"Power: pow(2, 3) = {pow(2, 3)}") # 8
print(f"Square root: math.sqrt(16) = {math.sqrt(16)}") # 4.0
# Check if number is integer
print(f"Is 3.0 integer? {3.0.is_integer()}") # True
print(f"Is 3.5 integer? {3.5.is_integer()}") # FalseType Conversion
Python allows you to convert between different number types, which is essential for mathematical operations and data processing.
# Converting between number types
# String to numbers
age_str = "25"
price_str = "19.99"
complex_str = "3+4j"
age = int(age_str) # String to integer
price = float(price_str) # String to float
z = complex(complex_str) # String to complex
print(f"age: {age}, type: {type(age)}") # 25, <class 'int'>
print(f"price: {price}, type: {type(price)}") # 19.99, <class 'float'>
print(f"z: {z}, type: {type(z)}") # (3+4j), <class 'complex'>
# Number to number conversions
pi_float = 3.14159
pi_int = int(pi_float) # Float to int (truncates decimal)
print(f"Pi as int: {pi_int}") # 3
large_int = 42
large_float = float(large_int) # Int to float
print(f"42 as float: {large_float}") # 42.0
# Number to string
temperature = -5
temp_str = str(temperature) # Number to string
print(f"Temperature as string: '{temp_str}'") # '-5'
# Automatic type promotion in operations
result = 5 + 3.2 # int + float = float
print(f"5 + 3.2 = {result}, type: {type(result)}") # 8.2, <class 'float'>
# Handling conversion errors
try:
invalid = int("hello") # This will raise ValueError
except ValueError as e:
print(f"Conversion error: {e}") # invalid literal for int()Understanding Python's number system is crucial for effective programming. Whether you're calculating finances, processing scientific data, or building games, these number types and operations form the foundation of mathematical programming in Python.