Working with Numbers in Python
Python provides comprehensive support for working with different types of numbers and mathematical operations. This guide covers numeric data types, operations, built-in functions, and advanced mathematical concepts in Python.
Table of Contents
1. [Numeric Data Types](#numeric-data-types) 2. [Basic Arithmetic Operations](#basic-arithmetic-operations) 3. [Built-in Mathematical Functions](#built-in-mathematical-functions) 4. [The Math Module](#the-math-module) 5. [Number Formatting and Conversion](#number-formatting-and-conversion) 6. [Advanced Number Operations](#advanced-number-operations) 7. [Random Numbers](#random-numbers) 8. [Decimal and Fraction Types](#decimal-and-fraction-types)
Numeric Data Types
Python supports several numeric data types, each designed for specific use cases and precision requirements.
Integer (int)
Integers are whole numbers without decimal points. Python 3 has arbitrary precision integers, meaning they can be as large as memory allows.
`python
Integer examples
positive_int = 42 negative_int = -17 zero = 0 large_int = 123456789012345678901234567890Different number bases
binary = 0b1010 # Binary (base 2) - equals 10 in decimal octal = 0o12 # Octal (base 8) - equals 10 in decimal hexadecimal = 0xa # Hexadecimal (base 16) - equals 10 in decimalprint(f"Binary {binary}, Octal {octal}, Hex {hexadecimal}")
`
Float (float)
Floating-point numbers represent real numbers with decimal points. Python uses double precision (64-bit) floating-point numbers.
`python
Float examples
simple_float = 3.14 scientific_notation = 1.23e-4 # 0.000123 negative_float = -2.5 infinity = float('inf') negative_infinity = float('-inf') not_a_number = float('nan')print(f"Scientific notation: {scientific_notation}")
print(f"Infinity: {infinity}")
print(f"NaN: {not_a_number}")
`
Complex (complex)
Complex numbers consist of real and imaginary parts, represented as a + bj where j is the imaginary unit.
`python
Complex number examples
complex1 = 3 + 4j complex2 = complex(2, -1) # 2 - 1j real_part = complex1.real imaginary_part = complex1.imagprint(f"Complex number: {complex1}")
print(f"Real part: {real_part}, Imaginary part: {imaginary_part}")
`
Data Type Comparison Table
| Type | Description | Example | Range/Precision | |------|-------------|---------|-----------------| | int | Whole numbers | 42, -17, 0 | Arbitrary precision | | float | Decimal numbers | 3.14, 1.23e-4 | ~15-17 decimal digits | | complex | Complex numbers | 3+4j, 2-1j | Two float components |
Basic Arithmetic Operations
Python supports standard arithmetic operations with specific behaviors and precedence rules.
Arithmetic Operators
`python
Basic arithmetic operations
a = 10 b = 3addition = a + b # 13 subtraction = a - b # 7 multiplication = a * b # 30 division = a / b # 3.3333333333333335 (float division) floor_division = a // b # 3 (integer division) modulus = a % b # 1 (remainder) exponentiation = a b # 1000 (10 to the power of 3)
print(f"Addition: {addition}")
print(f"Division: {division}")
print(f"Floor division: {floor_division}")
print(f"Modulus: {modulus}")
print(f"Exponentiation: {exponentiation}")
`
Operator Precedence
Understanding operator precedence is crucial for writing correct mathematical expressions.
| Precedence | Operator | Description | Example | |------------|----------|-------------|---------| | 1 (highest) | | Exponentiation | 2 3 2 = 512 | | 2 | +, - | Unary plus/minus | -5, +3 | | 3 | , /, //, % | Multiplication, Division | 6 2 / 3 = 4.0 | | 4 (lowest) | +, - | Addition, Subtraction | 5 + 3 - 2 = 6 |
`python
Demonstrating operator precedence
result1 = 2 + 3 * 4 # 14, not 20 result2 = (2 + 3) * 4 # 20 result3 = 2 3 2 # 512 (right associative) result4 = (2 3) 2 # 64print(f"2 + 3 * 4 = {result1}")
print(f"(2 + 3) * 4 = {result2}")
print(f"2 3 2 = {result3}")
print(f"(2 3) 2 = {result4}")
`
Augmented Assignment Operators
These operators perform an operation and assign the result back to the variable.
`python
Augmented assignment operators
x = 10 x += 5 # x = x + 5, result: 15 x -= 3 # x = x - 3, result: 12 x = 2 # x = x 2, result: 24 x /= 4 # x = x / 4, result: 6.0 x //= 2 # x = x // 2, result: 3.0 x %= 2 # x = x % 2, result: 1.0 x = 3 # x = x 3, result: 1.0print(f"Final value of x: {x}")
`
Built-in Mathematical Functions
Python provides several built-in functions for common mathematical operations.
Basic Mathematical Functions
`python
Built-in mathematical functions
numbers = [-5, -2.5, 0, 2.7, 10]Absolute value
abs_values = [abs(x) for x in numbers] print(f"Absolute values: {abs_values}")Rounding functions
value = 3.7 rounded_default = round(value) # 4 rounded_precision = round(3.14159, 2) # 3.14print(f"round(3.7): {rounded_default}") print(f"round(3.14159, 2): {rounded_precision}")
Min and max
min_value = min(numbers) # -5 max_value = max(numbers) # 10 print(f"Min: {min_value}, Max: {max_value}")Sum
total = sum(numbers) # 5.2 print(f"Sum: {total}")Power function
power_result = pow(2, 3) # 8 power_with_mod = pow(2, 3, 3) # (2^3) % 3 = 2 print(f"pow(2, 3): {power_result}") print(f"pow(2, 3, 3): {power_with_mod}")`Type Conversion Functions
`python
Type conversion functions
integer_value = int(3.7) # 3 (truncates) integer_from_string = int("42") # 42 float_value = float(42) # 42.0 float_from_string = float("3.14") # 3.14 complex_value = complex(3, 4) # (3+4j)print(f"int(3.7): {integer_value}") print(f"float(42): {float_value}") print(f"complex(3, 4): {complex_value}")
Binary, octal, and hexadecimal conversion
number = 42 binary_repr = bin(number) # '0b101010' octal_repr = oct(number) # '0o52' hex_repr = hex(number) # '0x2a'print(f"42 in binary: {binary_repr}")
print(f"42 in octal: {octal_repr}")
print(f"42 in hexadecimal: {hex_repr}")
`
The Math Module
The math module provides access to mathematical functions and constants for more advanced operations.
Mathematical Constants
`python
import math
Mathematical constants
print(f"Pi: {math.pi}") # 3.141592653589793 print(f"Euler's number: {math.e}") # 2.718281828459045 print(f"Tau (2*pi): {math.tau}") # 6.283185307179586 print(f"Infinity: {math.inf}") # inf print(f"NaN: {math.nan}") # nan`Trigonometric Functions
`python
import math
Trigonometric functions (angles in radians)
angle_degrees = 45 angle_radians = math.radians(angle_degrees)sin_value = math.sin(angle_radians) # 0.7071067811865476 cos_value = math.cos(angle_radians) # 0.7071067811865476 tan_value = math.tan(angle_radians) # 0.9999999999999999
print(f"sin(45°): {sin_value}") print(f"cos(45°): {cos_value}") print(f"tan(45°): {tan_value}")
Inverse trigonometric functions
asin_value = math.asin(0.5) # Returns radians asin_degrees = math.degrees(asin_value) # Convert to degreesprint(f"arcsin(0.5) in degrees: {asin_degrees}") # 30.0
`
Logarithmic and Exponential Functions
`python
import math
Logarithmic functions
value = 100 natural_log = math.log(value) # Natural logarithm (base e) log_base_10 = math.log10(value) # Logarithm base 10 log_base_2 = math.log2(value) # Logarithm base 2 custom_base_log = math.log(value, 3) # Logarithm base 3print(f"ln(100): {natural_log}") print(f"log10(100): {log_base_10}") print(f"log2(100): {log_base_2}") print(f"log3(100): {custom_base_log}")
Exponential functions
exp_value = math.exp(2) # e^2 exp2_value = math.exp2(3) # 2^3 pow_value = math.pow(2, 3) # 2^3 (returns float)print(f"e^2: {exp_value}")
print(f"2^3: {exp2_value}")
`
Other Useful Math Functions
`python
import math
Square root and power functions
sqrt_value = math.sqrt(16) # 4.0 cbrt_value = math.pow(27, 1/3) # Cube root: 3.0Ceiling and floor functions
ceiling_value = math.ceil(3.2) # 4 floor_value = math.floor(3.8) # 3Factorial
factorial_5 = math.factorial(5) # 120Greatest common divisor
gcd_value = math.gcd(48, 18) # 6print(f"sqrt(16): {sqrt_value}")
print(f"ceil(3.2): {ceiling_value}")
print(f"floor(3.8): {floor_value}")
print(f"5!: {factorial_5}")
print(f"gcd(48, 18): {gcd_value}")
`
Math Module Functions Summary
| Function | Description | Example |
|----------|-------------|---------|
| math.sqrt(x) | Square root | math.sqrt(16) → 4.0 |
| math.ceil(x) | Ceiling (round up) | math.ceil(3.2) → 4 |
| math.floor(x) | Floor (round down) | math.floor(3.8) → 3 |
| math.factorial(x) | Factorial | math.factorial(5) → 120 |
| math.gcd(a, b) | Greatest common divisor | math.gcd(48, 18) → 6 |
| math.sin(x) | Sine (radians) | math.sin(math.pi/2) → 1.0 |
| math.log(x) | Natural logarithm | math.log(math.e) → 1.0 |
| math.exp(x) | e raised to power x | math.exp(1) → 2.718... |
Number Formatting and Conversion
Python provides various methods to format and display numbers according to specific requirements.
String Formatting
`python
Different formatting methods
number = 3.14159265359Using format() method
formatted1 = "Value: {:.2f}".format(number) formatted2 = "Value: {:.4f}".format(number) formatted3 = "Value: {:10.2f}".format(number) # Width of 10, 2 decimalsprint(formatted1) # Value: 3.14 print(formatted2) # Value: 3.1416 print(formatted3) # Value: 3.14
Using f-strings (Python 3.6+)
f_string1 = f"Value: {number:.2f}" f_string2 = f"Value: {number:10.2f}" f_string3 = f"Scientific: {number:.2e}"print(f_string1) # Value: 3.14 print(f_string2) # Value: 3.14 print(f_string3) # Scientific: 3.14e+00
Percentage formatting
percentage = 0.1234 print(f"Percentage: {percentage:.1%}") # Percentage: 12.3%`Number Base Conversions
`python
Converting between different number bases
decimal_number = 42Convert to different bases
binary = bin(decimal_number) # '0b101010' octal = oct(decimal_number) # '0o52' hexadecimal = hex(decimal_number) # '0x2a'print(f"Decimal {decimal_number}:") print(f"Binary: {binary}") print(f"Octal: {octal}") print(f"Hexadecimal: {hexadecimal}")
Convert from other bases to decimal
binary_to_decimal = int('101010', 2) # 42 octal_to_decimal = int('52', 8) # 42 hex_to_decimal = int('2a', 16) # 42print(f"\nConverting back to decimal:")
print(f"Binary '101010': {binary_to_decimal}")
print(f"Octal '52': {octal_to_decimal}")
print(f"Hex '2a': {hex_to_decimal}")
`
Formatting Options Table
| Format Specifier | Description | Example | Result |
|------------------|-------------|---------|--------|
| :.2f | 2 decimal places | f"{3.14159:.2f}" | "3.14" |
| :10.2f | Width 10, 2 decimals | f"{3.14:.10.2f}" | " 3.14" |
| :.2e | Scientific notation | f"{314.159:.2e}" | "3.14e+02" |
| :.1% | Percentage | f"{0.123:.1%}" | "12.3%" |
| :, | Thousands separator | f"{1234567:,}" | "1,234,567" |
| :08d | Zero-padded integer | f"{42:08d}" | "00000042" |
Advanced Number Operations
Working with Complex Numbers
`python
Complex number operations
z1 = 3 + 4j z2 = 1 - 2jBasic operations
addition = z1 + z2 # (4+2j) multiplication = z1 * z2 # (11-2j) division = z1 / z2 # (-1+2j)Complex number properties
magnitude = abs(z1) # 5.0 conjugate = z1.conjugate() # (3-4j)print(f"z1 + z2 = {addition}") print(f"z1 * z2 = {multiplication}") print(f"|z1| = {magnitude}") print(f"z1* = {conjugate}")
Polar form conversion
import cmath polar_form = cmath.polar(z1) # (magnitude, phase) rectangular_form = cmath.rect(polar_form[0], polar_form[1])print(f"Polar form: {polar_form}")
print(f"Back to rectangular: {rectangular_form}")
`
Bitwise Operations
`python
Bitwise operations on integers
a = 60 # 111100 in binary b = 13 # 001101 in binarybitwise_and = a & b # 12 (001100) bitwise_or = a | b # 61 (111101) bitwise_xor = a ^ b # 49 (110001) bitwise_not = ~a # -61 (two's complement) left_shift = a << 2 # 240 (11110000) right_shift = a >> 2 # 15 (001111)
print(f"a & b = {bitwise_and}")
print(f"a | b = {bitwise_or}")
print(f"a ^ b = {bitwise_xor}")
print(f"~a = {bitwise_not}")
print(f"a << 2 = {left_shift}")
print(f"a >> 2 = {right_shift}")
`
Random Numbers
The random module provides functions for generating random numbers and making random choices.
Basic Random Number Generation
`python
import random
Random float between 0.0 and 1.0
random_float = random.random() print(f"Random float: {random_float}")Random integer in a range
random_int = random.randint(1, 10) # Inclusive of both endpoints print(f"Random integer (1-10): {random_int}")Random choice from a sequence
choices = ['apple', 'banana', 'cherry'] random_choice = random.choice(choices) print(f"Random choice: {random_choice}")Random float in a range
random_uniform = random.uniform(1.5, 10.5) print(f"Random uniform (1.5-10.5): {random_uniform}")Random integer with step
random_range = random.randrange(0, 100, 5) # 0, 5, 10, ..., 95 print(f"Random range (0-100, step 5): {random_range}")`Advanced Random Operations
`python
import random
Shuffling a list
numbers = list(range(1, 11)) print(f"Original list: {numbers}") random.shuffle(numbers) print(f"Shuffled list: {numbers}")Random sampling
sample = random.sample(numbers, 3) # 3 unique elements print(f"Random sample: {sample}")Setting seed for reproducible results
random.seed(42) reproducible1 = random.random() random.seed(42) reproducible2 = random.random() print(f"Same seed results: {reproducible1} == {reproducible2}")Gaussian (normal) distribution
gaussian = random.gauss(0, 1) # Mean=0, Standard deviation=1 print(f"Gaussian random: {gaussian}")`Decimal and Fraction Types
For applications requiring exact decimal representation or rational number arithmetic, Python provides the decimal and fractions modules.
Decimal Module
`python
from decimal import Decimal, getcontext
Setting precision
getcontext().prec = 10Creating Decimal objects
d1 = Decimal('0.1') d2 = Decimal('0.2') d3 = Decimal(0.1) # Not recommended due to float precision issuesprint(f"Decimal('0.1') + Decimal('0.2') = {d1 + d2}") print(f"Regular float: {0.1 + 0.2}")
Decimal arithmetic maintains precision
precise_division = Decimal('1') / Decimal('3') print(f"1/3 with 10 decimal places: {precise_division}")Rounding with Decimal
from decimal import ROUND_HALF_UP, ROUND_DOWN value = Decimal('2.675') rounded_up = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) rounded_down = value.quantize(Decimal('0.01'), rounding=ROUND_DOWN)print(f"2.675 rounded half up: {rounded_up}")
print(f"2.675 rounded down: {rounded_down}")
`
Fractions Module
`python
from fractions import Fraction
Creating fractions
f1 = Fraction(1, 3) # 1/3 f2 = Fraction(2, 6) # 2/6 = 1/3 f3 = Fraction('0.25') # 1/4 f4 = Fraction(0.125) # 1/8print(f"1/3 = {f1}") print(f"2/6 simplified = {f2}") print(f"0.25 as fraction = {f3}") print(f"0.125 as fraction = {f4}")
Fraction arithmetic
sum_fractions = f1 + f3 # 1/3 + 1/4 = 7/12 product = f1 f4 # 1/3 1/8 = 1/24print(f"1/3 + 1/4 = {sum_fractions}") print(f"1/3 * 1/8 = {product}")
Converting to float
float_value = float(f1) print(f"1/3 as float: {float_value}")Limiting denominator
pi_fraction = Fraction(3.14159).limit_denominator(100) print(f"π approximation: {pi_fraction}")`Practical Examples and Applications
Statistical Calculations
`python
import math
def calculate_statistics(numbers): """Calculate basic statistics for a list of numbers.""" n = len(numbers) # Mean mean = sum(numbers) / n # Median sorted_numbers = sorted(numbers) if n % 2 == 0: median = (sorted_numbers[n//2 - 1] + sorted_numbers[n//2]) / 2 else: median = sorted_numbers[n//2] # Standard deviation variance = sum((x - mean) 2 for x in numbers) / n std_dev = math.sqrt(variance) return { 'mean': mean, 'median': median, 'std_dev': std_dev, 'min': min(numbers), 'max': max(numbers) }
Example usage
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] stats = calculate_statistics(data)for key, value in stats.items():
print(f"{key.capitalize()}: {value:.2f}")
`
Financial Calculations
`python
from decimal import Decimal, ROUND_HALF_UP
def compound_interest(principal, rate, time, compounds_per_year=1): """Calculate compound interest using Decimal for precision.""" p = Decimal(str(principal)) r = Decimal(str(rate)) t = Decimal(str(time)) n = Decimal(str(compounds_per_year)) # A = P(1 + r/n)^(nt) amount = p (1 + r/n) (n t) interest = amount - p return { 'principal': p, 'amount': amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP), 'interest': interest.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) }
Example: $1000 at 5% annual interest for 3 years, compounded quarterly
result = compound_interest(1000, 0.05, 3, 4) print(f"Principal: ${result['principal']}") print(f"Final Amount: ${result['amount']}") print(f"Interest Earned: ${result['interest']}")`This comprehensive guide covers the essential aspects of working with numbers in Python, from basic arithmetic to advanced mathematical operations and specialized numeric types. Understanding these concepts will enable you to perform accurate calculations and handle various numerical requirements in your Python programs.