Basic Math Operations in Python
Table of Contents
1. [Introduction](#introduction) 2. [Arithmetic Operators](#arithmetic-operators) 3. [Mathematical Functions](#mathematical-functions) 4. [Built-in Math Functions](#built-in-math-functions) 5. [The Math Module](#the-math-module) 6. [Order of Operations](#order-of-operations) 7. [Working with Different Number Types](#working-with-different-number-types) 8. [Advanced Mathematical Operations](#advanced-mathematical-operations) 9. [Practical Examples](#practical-examples) 10. [Best Practices and Common Pitfalls](#best-practices-and-common-pitfalls)Introduction
Python provides comprehensive support for mathematical operations, from basic arithmetic to complex mathematical functions. Understanding these operations is fundamental for any Python programmer, whether you're working on simple calculations or complex scientific computations. Python's mathematical capabilities are built into the language itself, with additional functionality available through modules like math, decimal, and fractions.
Python treats numbers as first-class objects, meaning they can be assigned to variables, passed as arguments to functions, and returned from functions. The language supports several numeric types including integers, floating-point numbers, and complex numbers, each with their own characteristics and use cases.
Arithmetic Operators
Basic Arithmetic Operators
Python provides seven fundamental arithmetic operators that form the foundation of mathematical operations:
| Operator | Name | Description | Example | Result |
|----------|------|-------------|---------|--------|
| + | Addition | Adds two operands | 5 + 3 | 8 |
| - | Subtraction | Subtracts right operand from left | 10 - 4 | 6 |
| | Multiplication | Multiplies two operands | 6 7 | 42 |
| / | Division | Divides left operand by right (float result) | 15 / 4 | 3.75 |
| // | Floor Division | Divides and returns largest integer ≤ result | 15 // 4 | 3 |
| % | Modulus | Returns remainder of division | 15 % 4 | 3 |
| | Exponentiation | Raises left operand to power of right | 2 3 | 8 |
Detailed Operator Explanations
#### Addition Operator (+) The addition operator performs standard mathematical addition between two numbers. It can work with integers, floats, and even complex numbers.
`python
Integer addition
result1 = 10 + 5 print(result1) # Output: 15Float addition
result2 = 3.14 + 2.86 print(result2) # Output: 6.0Mixed type addition
result3 = 10 + 3.5 print(result3) # Output: 13.5Complex number addition
result4 = (3 + 4j) + (1 + 2j) print(result4) # Output: (4+6j)`#### Subtraction Operator (-) The subtraction operator subtracts the right operand from the left operand. It can also be used as a unary operator to negate a number.
`python
Basic subtraction
result1 = 20 - 8 print(result1) # Output: 12Unary minus (negation)
positive_num = 15 negative_num = -positive_num print(negative_num) # Output: -15Subtraction with floats
result2 = 10.5 - 3.2 print(result2) # Output: 7.3`#### Multiplication Operator (*) The multiplication operator multiplies two operands together.
`python
Integer multiplication
result1 = 6 * 8 print(result1) # Output: 48Float multiplication
result2 = 2.5 * 4.0 print(result2) # Output: 10.0String repetition (special case)
repeated_string = "Hello " * 3 print(repeated_string) # Output: Hello Hello Hello`#### Division Operator (/) The division operator always returns a float result, even when dividing two integers.
`python
Integer division (returns float)
result1 = 10 / 2 print(result1) # Output: 5.0 print(type(result1)) # Output:Float division
result2 = 15.6 / 3.0 print(result2) # Output: 5.2Division by zero raises ZeroDivisionError
try: result3 = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")`#### Floor Division Operator (//) Floor division returns the largest integer less than or equal to the division result.
`python
Positive numbers
result1 = 17 // 5 print(result1) # Output: 3With floats
result2 = 17.0 // 5.0 print(result2) # Output: 3.0Negative numbers (important behavior)
result3 = -17 // 5 print(result3) # Output: -4 (not -3)result4 = 17 // -5
print(result4) # Output: -4
`
#### Modulus Operator (%) The modulus operator returns the remainder after division.
`python
Basic modulus
result1 = 17 % 5 print(result1) # Output: 2Even/odd checking
number = 15 if number % 2 == 0: print("Even") else: print("Odd") # This will be printedCycling through values
for i in range(10): day_of_week = i % 7 print(f"Day {i}: {day_of_week}")`#### Exponentiation Operator () The exponentiation operator raises the left operand to the power of the right operand.
`python
Basic exponentiation
result1 = 2 3 print(result1) # Output: 8Square root (using fractional exponent)
result2 = 16 0.5 print(result2) # Output: 4.0Large numbers
result3 = 10 100 print(len(str(result3))) # Python handles arbitrarily large integersNegative exponents
result4 = 2 -3 print(result4) # Output: 0.125`Mathematical Functions
Built-in Math Functions
Python provides several built-in mathematical functions that don't require importing any modules:
| Function | Description | Example | Result |
|----------|-------------|---------|--------|
| abs(x) | Absolute value | abs(-5) | 5 |
| round(x, n) | Round to n decimal places | round(3.14159, 2) | 3.14 |
| min(x, y, ...) | Minimum value | min(3, 7, 1, 9) | 1 |
| max(x, y, ...) | Maximum value | max(3, 7, 1, 9) | 9 |
| sum(iterable) | Sum of all elements | sum([1, 2, 3, 4]) | 10 |
| pow(x, y) | x raised to power y | pow(2, 3) | 8 |
| divmod(x, y) | Quotient and remainder | divmod(17, 5) | (3, 2) |
Detailed Function Explanations
#### Absolute Value Function
The abs() function returns the absolute value of a number, which is its distance from zero.
`python
Integer absolute value
result1 = abs(-10) print(result1) # Output: 10result2 = abs(10) print(result2) # Output: 10
Float absolute value
result3 = abs(-3.14) print(result3) # Output: 3.14Complex number absolute value (magnitude)
result4 = abs(3 + 4j) print(result4) # Output: 5.0 (sqrt(3^2 + 4^2))`#### Rounding Function
The round() function rounds a number to a specified number of decimal places.
`python
Default rounding (to nearest integer)
result1 = round(3.7) print(result1) # Output: 4result2 = round(3.2) print(result2) # Output: 3
Rounding to specific decimal places
result3 = round(3.14159, 2) print(result3) # Output: 3.14result4 = round(3.14159, 4) print(result4) # Output: 3.1416
Rounding to tens, hundreds, etc.
result5 = round(1234.5678, -1) print(result5) # Output: 1230.0result6 = round(1234.5678, -2)
print(result6) # Output: 1200.0
`
#### Min and Max Functions These functions find the minimum and maximum values from a collection of numbers.
`python
Multiple arguments
min_val = min(5, 2, 8, 1, 9) print(min_val) # Output: 1max_val = max(5, 2, 8, 1, 9) print(max_val) # Output: 9
With iterables
numbers = [3.5, 2.1, 4.8, 1.2, 6.9] min_val2 = min(numbers) max_val2 = max(numbers) print(f"Min: {min_val2}, Max: {max_val2}") # Output: Min: 1.2, Max: 6.9With strings (lexicographic order)
min_str = min("hello", "world", "python") print(min_str) # Output: hello`The Math Module
The math module provides access to mathematical functions and constants beyond the built-in functions. To use it, you must import it first.
`python
import math
`
Mathematical Constants
| Constant | Description | Value |
|----------|-------------|-------|
| math.pi | Pi (π) | 3.141592653589793 |
| math.e | Euler's number (e) | 2.718281828459045 |
| math.tau | Tau (2π) | 6.283185307179586 |
| math.inf | Positive infinity | inf |
| math.nan | Not a Number | nan |
Trigonometric Functions
| Function | Description | Example |
|----------|-------------|---------|
| math.sin(x) | Sine of x (in radians) | math.sin(math.pi/2) → 1.0 |
| math.cos(x) | Cosine of x (in radians) | math.cos(0) → 1.0 |
| math.tan(x) | Tangent of x (in radians) | math.tan(math.pi/4) → 1.0 |
| math.asin(x) | Arc sine of x | math.asin(1) → 1.5707963267948966 |
| math.acos(x) | Arc cosine of x | math.acos(1) → 0.0 |
| math.atan(x) | Arc tangent of x | math.atan(1) → 0.7853981633974483 |
`python
import math
Converting degrees to radians
degrees = 45 radians = math.radians(degrees) print(f"{degrees} degrees = {radians} radians")Trigonometric calculations
sin_45 = math.sin(radians) cos_45 = math.cos(radians) tan_45 = math.tan(radians)print(f"sin(45°) = {sin_45:.4f}") print(f"cos(45°) = {cos_45:.4f}") print(f"tan(45°) = {tan_45:.4f}")
Converting radians back to degrees
degrees_back = math.degrees(radians) print(f"{radians} radians = {degrees_back} degrees")`Logarithmic and Exponential Functions
| Function | Description | Example |
|----------|-------------|---------|
| math.log(x) | Natural logarithm | math.log(math.e) → 1.0 |
| math.log10(x) | Base-10 logarithm | math.log10(100) → 2.0 |
| math.log2(x) | Base-2 logarithm | math.log2(8) → 3.0 |
| math.exp(x) | e raised to power x | math.exp(1) → 2.718281828459045 |
| math.pow(x, y) | x raised to power y | math.pow(2, 3) → 8.0 |
`python
import math
Natural logarithm
result1 = math.log(10) print(f"ln(10) = {result1:.4f}")Logarithm with custom base
def log_base(x, base): return math.log(x) / math.log(base)result2 = log_base(8, 2) print(f"log₂(8) = {result2}")
Exponential function
result3 = math.exp(2) print(f"e² = {result3:.4f}")Power function
result4 = math.pow(2.5, 3.2) print(f"2.5^3.2 = {result4:.4f}")`Other Useful Math Functions
| 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(12, 18) → 6 |
| math.fabs(x) | Absolute value (float) | math.fabs(-3.5) → 3.5 |
`python
import math
Square root
result1 = math.sqrt(25) print(f"√25 = {result1}")Ceiling and floor
number = 3.7 ceil_result = math.ceil(number) floor_result = math.floor(number) print(f"ceil({number}) = {ceil_result}") print(f"floor({number}) = {floor_result}")Factorial
factorial_5 = math.factorial(5) print(f"5! = {factorial_5}")Greatest common divisor
gcd_result = math.gcd(48, 18) print(f"gcd(48, 18) = {gcd_result}")Least common multiple (using gcd)
def lcm(a, b): return abs(a * b) // math.gcd(a, b)lcm_result = lcm(12, 18)
print(f"lcm(12, 18) = {lcm_result}")
`
Order of Operations
Python follows the standard mathematical order of operations, often remembered by the acronym PEMDAS:
1. Parentheses - ()
2. Exponents -
3. Multiplication and Division - *, /, //, % (left to right)
4. Addition and Subtraction - +, - (left to right)
Order of Operations Examples
`python
Without parentheses
result1 = 2 + 3 * 4 print(result1) # Output: 14 (not 20)With parentheses
result2 = (2 + 3) * 4 print(result2) # Output: 20Complex expression
result3 = 2 3 * 4 + 5 print(result3) # Output: 37 (8 * 4 + 5)Step by step breakdown
expression = 2 + 3 4 * 2 - 1Step 1: 4 2 = 16
Step 2: 3 * 16 = 48
Step 3: 2 + 48 = 50
Step 4: 50 - 1 = 49
print(expression) # Output: 49Using parentheses to change order
result4 = ((2 + 3) 4) * 2 - 1 print(result4) # Output: 399`Working with Different Number Types
Integer Operations
Python 3 integers have unlimited precision, meaning they can be arbitrarily large.
`python
Large integer calculations
large_num1 = 123456789012345678901234567890 large_num2 = 987654321098765432109876543210 large_sum = large_num1 + large_num2 print(f"Large sum: {large_sum}")Integer division behavior
print(f"10 / 3 = {10 / 3}") # Output: 3.3333333333333335 print(f"10 // 3 = {10 // 3}") # Output: 3 print(f"10 % 3 = {10 % 3}") # Output: 1Binary, octal, and hexadecimal
binary_num = 0b1010 # Binary representation of 10 octal_num = 0o12 # Octal representation of 10 hex_num = 0xa # Hexadecimal representation of 10 print(f"Binary 1010 = {binary_num}") print(f"Octal 12 = {octal_num}") print(f"Hex a = {hex_num}")`Floating-Point Operations
Floating-point numbers in Python are implemented using the IEEE 754 double precision format.
`python
Floating-point precision
result1 = 0.1 + 0.2 print(f"0.1 + 0.2 = {result1}") # Output: 0.30000000000000004Comparing floats (problematic)
if result1 == 0.3: print("Equal") else: print("Not equal") # This will be printedBetter way to compare floats
import math if math.isclose(result1, 0.3): print("Close enough") # This will be printedScientific notation
scientific_num = 1.23e-4 print(f"Scientific notation: {scientific_num}") # Output: 0.000123Float special values
positive_inf = float('inf') negative_inf = float('-inf') not_a_number = float('nan')print(f"Positive infinity: {positive_inf}") print(f"Negative infinity: {negative_inf}") print(f"Not a number: {not_a_number}")
Checking for special values
print(f"Is inf finite? {math.isfinite(positive_inf)}") print(f"Is nan a number? {math.isnan(not_a_number)}")`Complex Number Operations
Python has built-in support for complex numbers using the j suffix for the imaginary part.
`python
Creating complex numbers
complex1 = 3 + 4j complex2 = 1 - 2j complex3 = complex(2, 5) # Alternative creation methodprint(f"Complex1: {complex1}") print(f"Complex2: {complex2}") print(f"Complex3: {complex3}")
Complex number operations
addition = complex1 + complex2 multiplication = complex1 * complex2 division = complex1 / complex2print(f"Addition: {addition}") print(f"Multiplication: {multiplication}") print(f"Division: {division}")
Accessing real and imaginary parts
print(f"Real part of complex1: {complex1.real}") print(f"Imaginary part of complex1: {complex1.imag}")Complex conjugate
conjugate = complex1.conjugate() print(f"Conjugate of {complex1}: {conjugate}")Magnitude (absolute value)
magnitude = abs(complex1) print(f"Magnitude of {complex1}: {magnitude}")`Advanced Mathematical Operations
Statistical Operations
`python
import math
import statistics
Dataset for examples
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Mean (average)
mean_value = statistics.mean(data) print(f"Mean: {mean_value}")Median
median_value = statistics.median(data) print(f"Median: {median_value}")Mode (most common value)
mode_data = [1, 2, 2, 3, 4, 4, 4, 5] mode_value = statistics.mode(mode_data) print(f"Mode: {mode_value}")Standard deviation
stdev_value = statistics.stdev(data) print(f"Standard deviation: {stdev_value:.4f}")Variance
variance_value = statistics.variance(data) print(f"Variance: {variance_value:.4f}")`Number Base Conversions
`python
Converting between number bases
decimal_num = 255Convert to binary, octal, and hexadecimal
binary_str = bin(decimal_num) octal_str = oct(decimal_num) hex_str = hex(decimal_num)print(f"Decimal {decimal_num}:") print(f"Binary: {binary_str}") print(f"Octal: {octal_str}") print(f"Hexadecimal: {hex_str}")
Convert back to decimal
binary_to_decimal = int('11111111', 2) octal_to_decimal = int('377', 8) hex_to_decimal = int('ff', 16)print(f"\nConverting back to decimal:") print(f"Binary 11111111 = {binary_to_decimal}") print(f"Octal 377 = {octal_to_decimal}") print(f"Hex ff = {hex_to_decimal}")
Custom base conversion
def convert_base(number, from_base, to_base): # Convert to decimal first decimal = int(str(number), from_base) # Convert from decimal to target base if to_base == 10: return decimal digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" while decimal > 0: result = digits[decimal % to_base] + result decimal //= to_base return result if result else "0"Example: Convert binary 1010 to base 5
result = convert_base(1010, 2, 5) print(f"Binary 1010 in base 5: {result}")`Practical Examples
Financial Calculations
`python
import math
def compound_interest(principal, rate, time, n=1): """ Calculate compound interest principal: initial amount rate: annual interest rate (as decimal) time: time in years n: number of times interest is compounded per year """ amount = principal (1 + rate/n) (n time) return amount
def simple_interest(principal, rate, time): """Calculate simple interest""" return principal (1 + rate time)
def loan_payment(principal, rate, periods): """Calculate monthly loan payment""" if rate == 0: return principal / periods monthly_rate = rate / 12 payment = principal (monthly_rate (1 + monthly_rate) periods) / \ ((1 + monthly_rate) periods - 1) return payment
Examples
principal = 10000 annual_rate = 0.05 years = 5compound_amount = compound_interest(principal, annual_rate, years, 12) simple_amount = simple_interest(principal, annual_rate, years)
print(f"Principal: ${principal:,.2f}") print(f"Compound interest (monthly): ${compound_amount:,.2f}") print(f"Simple interest: ${simple_amount:,.2f}") print(f"Difference: ${compound_amount - simple_amount:,.2f}")
Loan payment calculation
loan_amount = 200000 annual_rate = 0.04 years = 30 monthly_payment = loan_payment(loan_amount, annual_rate, years * 12) print(f"\nLoan payment for ${loan_amount:,.2f} at {annual_rate*100}% for {years} years:") print(f"Monthly payment: ${monthly_payment:,.2f}")`Geometric Calculations
`python
import math
def circle_area(radius): """Calculate area of a circle""" return math.pi radius * 2
def circle_circumference(radius): """Calculate circumference of a circle""" return 2 math.pi radius
def triangle_area(base, height): """Calculate area of a triangle""" return 0.5 base height
def triangle_area_heron(a, b, c): """Calculate triangle area using Heron's formula""" s = (a + b + c) / 2 # semi-perimeter return math.sqrt(s (s - a) (s - b) * (s - c))
def distance_2d(x1, y1, x2, y2): """Calculate distance between two points in 2D""" return math.sqrt((x2 - x1) 2 + (y2 - y1) 2)
def sphere_volume(radius): """Calculate volume of a sphere""" return (4/3) math.pi radius 3
def cylinder_volume(radius, height): """Calculate volume of a cylinder""" return math.pi radius 2 height
Examples
radius = 5 print(f"Circle with radius {radius}:") print(f"Area: {circle_area(radius):.2f}") print(f"Circumference: {circle_circumference(radius):.2f}")Triangle with sides 3, 4, 5
sides = (3, 4, 5) area_heron = triangle_area_heron(*sides) print(f"\nTriangle with sides {sides}:") print(f"Area (Heron's formula): {area_heron:.2f}")Distance between points
point1 = (0, 0) point2 = (3, 4) distance = distance_2d(point1, point2) print(f"\nDistance between {point1} and {point2}: {distance:.2f}")3D shapes
sphere_vol = sphere_volume(radius) cylinder_vol = cylinder_volume(radius, 10) print(f"\nSphere volume (r={radius}): {sphere_vol:.2f}") print(f"Cylinder volume (r={radius}, h=10): {cylinder_vol:.2f}")`Number Theory Operations
`python
import math
def is_prime(n): """Check if a number is prime""" if n < 2: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True
def prime_factors(n): """Find prime factors of a number""" factors = [] d = 2 while d * d <= n: while n % d == 0: factors.append(d) n //= d d += 1 if n > 1: factors.append(n) return factors
def fibonacci(n): """Generate first n Fibonacci numbers""" if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] fib = [0, 1] for i in range(2, n): fib.append(fib[i-1] + fib[i-2]) return fib
def gcd_extended(a, b): """Extended Euclidean algorithm""" if a == 0: return b, 0, 1 gcd, x1, y1 = gcd_extended(b % a, a) x = y1 - (b // a) * x1 y = x1 return gcd, x, y
Examples
test_numbers = [17, 25, 29, 100] for num in test_numbers: print(f"{num} is prime: {is_prime(num)}")print(f"\nPrime factors of 60: {prime_factors(60)}") print(f"Prime factors of 100: {prime_factors(100)}")
print(f"\nFirst 10 Fibonacci numbers: {fibonacci(10)}")
Extended GCD
a, b = 35, 15 gcd_val, x, y = gcd_extended(a, b) print(f"\nExtended GCD of {a} and {b}:") print(f"GCD: {gcd_val}") print(f"Coefficients: x={x}, y={y}") print(f"Verification: {a}{x} + {b}{y} = {ax + by}")`Best Practices and Common Pitfalls
Floating-Point Precision Issues
`python
import math
from decimal import Decimal, getcontext
Problem: Floating-point precision
result = 0.1 + 0.2 print(f"0.1 + 0.2 = {result}") print(f"Is it equal to 0.3? {result == 0.3}")Solution 1: Using math.isclose()
print(f"Using math.isclose(): {math.isclose(result, 0.3)}")Solution 2: Using decimal module for exact arithmetic
getcontext().prec = 50 # Set precision decimal_result = Decimal('0.1') + Decimal('0.2') print(f"Using Decimal: {decimal_result}") print(f"Is it equal to 0.3? {decimal_result == Decimal('0.3')}")Solution 3: Rounding for display
print(f"Rounded result: {round(result, 1)}")`Division by Zero Handling
`python
def safe_division(dividend, divisor):
"""Safely perform division with error handling"""
try:
result = dividend / divisor
return result
except ZeroDivisionError:
print(f"Error: Cannot divide {dividend} by zero")
return None
def safe_modulus(dividend, divisor): """Safely perform modulus operation""" try: result = dividend % divisor return result except ZeroDivisionError: print(f"Error: Cannot find remainder of {dividend} divided by zero") return None
Examples
print(safe_division(10, 2)) # Output: 5.0 print(safe_division(10, 0)) # Output: Error message and None print(safe_modulus(10, 3)) # Output: 1 print(safe_modulus(10, 0)) # Output: Error message and None`Performance Considerations
`python
import time
import math
def timing_comparison(): """Compare performance of different mathematical operations""" n = 1000000 # Test 1: vs math.pow vs pow start_time = time.time() for i in range(n): result = 2 3 time_operator = time.time() - start_time start_time = time.time() for i in range(n): result = math.pow(2, 3) time_math_pow = time.time() - start_time start_time = time.time() for i in range(n): result = pow(2, 3) time_builtin_pow = time.time() - start_time print("Power operation performance:") print(f" operator: {time_operator:.4f} seconds") print(f"math.pow(): {time_math_pow:.4f} seconds") print(f"pow() builtin: {time_builtin_pow:.4f} seconds") # Test 2: Square root comparison start_time = time.time() for i in range(n): result = math.sqrt(16) time_sqrt = time.time() - start_time start_time = time.time() for i in range(n): result = 16 0.5 time_power = time.time() - start_time print("\nSquare root performance:") print(f"math.sqrt(): {time_sqrt:.4f} seconds") print(f" 0.5: {time_power:.4f} seconds")
Run timing comparison
timing_comparison()`Input Validation for Mathematical Functions
`python
import math
def validated_sqrt(x): """Square root with input validation""" if not isinstance(x, (int, float)): raise TypeError("Input must be a number") if x < 0: raise ValueError("Cannot compute square root of negative number") return math.sqrt(x)
def validated_log(x, base=math.e): """Logarithm with input validation""" if not isinstance(x, (int, float)) or not isinstance(base, (int, float)): raise TypeError("Inputs must be numbers") if x <= 0: raise ValueError("Logarithm input must be positive") if base <= 0 or base == 1: raise ValueError("Logarithm base must be positive and not equal to 1") if base == math.e: return math.log(x) else: return math.log(x) / math.log(base)
def validated_factorial(n): """Factorial with input validation""" if not isinstance(n, int): raise TypeError("Factorial input must be an integer") if n < 0: raise ValueError("Factorial is not defined for negative numbers") return math.factorial(n)
Examples with error handling
test_cases = [ (validated_sqrt, [16, -4, "invalid"]), (validated_log, [10, 0, -5]), (validated_factorial, [5, -3, 3.14]) ]for func, test_values in test_cases:
print(f"\nTesting {func.__name__}:")
for value in test_values:
try:
result = func(value)
print(f" {func.__name__}({value}) = {result}")
except (TypeError, ValueError) as e:
print(f" {func.__name__}({value}) -> Error: {e}")
`
This comprehensive guide covers the fundamental mathematical operations in Python, from basic arithmetic to advanced mathematical functions. Understanding these concepts and their proper implementation is crucial for any Python programmer working with numerical data or mathematical computations. The examples and best practices provided should help you avoid common pitfalls and write more robust mathematical code.