Mathematical Functions

1. abs()

Syntax: abs(x)
Description: Returns the absolute value (non-negative value) of a number.

Examples:

python

# 1. Basic negative numbers
print(abs(-10))          # 10

# 2. Positive numbers remain unchanged
print(abs(5.5))          # 5.5

# 3. Floating point negative numbers
print(abs(-3.14))        # 3.14

# 4. Zero remains zero
print(abs(0))            # 0

# 5. Complex numbers (returns magnitude)
print(abs(3 + 4j))       # 5.0

# 6. With expressions
print(abs(-100 + 50))    # 50

# 7. Large negative numbers
print(abs(-999999))      # 999999

# 8. Decimal numbers
print(abs(-0.001))       # 0.001

# 9. With variables
x = -15
print(abs(x))            # 15

# 10. Nested expressions
print(abs(abs(-20) - abs(10)))  # 10

2. max()

Syntax: max(iterable, *iterables, key, default) or max(arg1, arg2, *args, key)
Description: Returns the largest item from iterable or arguments.

Examples:

python

# 1. Multiple arguments
print(max(1, 5, 2))              # 5

# 2. List of numbers
print(max([10, 3, 8, 15]))       # 15

# 3. Strings (lexicographical order)
print(max("hello", "world"))     # 'world'

# 4. Empty iterable with default
print(max([], default=0))        # 0

# 5. Using key function
print(max([1, 2, 3], key=lambda x: -x))  # 1

# 6. Tuple of numbers
print(max((4.5, 2.8, 9.1)))      # 9.1

# 7. Multiple iterables
print(max([1, 2], [3, 1]))       # [3, 1]

# 8. With negative numbers
print(max(-10, -5, -1))          # -1

# 9. Strings in list
print(max(["apple", "banana", "cherry"]))  # 'cherry'

# 10. Using key with custom objects
words = ["cat", "elephant", "dog"]
print(max(words, key=len))       # 'elephant'

3. min()

Syntax: min(iterable, *iterables, key, default) or min(arg1, arg2, *args, key)
Description: Returns the smallest item from iterable or arguments.

Examples:

python

# 1. Multiple arguments
print(min(1, 5, 2))              # 1

# 2. List of numbers
print(min([10, 3, 8, 15]))       # 3

# 3. Strings (lexicographical order)
print(min("hello", "world"))     # 'hello'

# 4. Empty iterable with default
print(min([], default=100))      # 100

# 5. Using key function
print(min([1, 2, 3], key=lambda x: -x))  # 3

# 6. Tuple of numbers
print(min((4.5, 2.8, 9.1)))      # 2.8

# 7. Multiple iterables
print(min([1, 2], [3, 1]))       # [1, 2]

# 8. With negative numbers
print(min(-10, -5, -1))          # -10

# 9. Strings in list
print(min(["apple", "banana", "cherry"]))  # 'apple'

# 10. Using key with custom objects
words = ["cat", "elephant", "dog"]
print(min(words, key=len))       # 'cat'

4. round()

Syntax: round(number, ndigits=None)
Description: Rounds a number to specified decimal places.

Examples:

python

# 1. Two decimal places
print(round(3.14159, 2))         # 3.14

# 2. Default rounding (to integer)
print(round(2.5))                # 2

# 3. Bankers rounding (rounds to nearest even)
print(round(3.5))                # 4

# 4. Round to tens place
print(round(123.456, -1))        # 120.0

# 5. Round to integer (explicit)
print(round(123.456, 0))         # 123.0

# 6. Negative decimal rounding
print(round(1234.567, -2))       # 1200.0

# 7. Exact halfway case
print(round(4.5))                # 4

# 8. Multiple decimal places
print(round(1.23456789, 4))      # 1.2346

# 9. Rounding negative numbers
print(round(-2.7))               # -3

# 10. Complex rounding scenario
print(round(123.456789, 3))      # 123.457

5. sum()

Syntax: sum(iterable, start=0)
Description: Returns the sum of all items in an iterable.

Examples:

python

# 1. Basic list sum
print(sum([1, 2, 3]))            # 6

# 2. With start value
print(sum([1, 2, 3], 10))        # 16

# 3. Tuple of floats
print(sum((4.5, 2.5, 1.0)))      # 8.0

# 4. Sum of dictionary keys
print(sum({1: 'a', 2: 'b'}))     # 3

# 5. Range sum
print(sum(range(1, 6)))          # 15

# 6. Empty iterable
print(sum([]))                   # 0

# 7. With negative start
print(sum([1, 2, 3], -5))        # 1

# 8. List of lists (flatten and sum)
print(sum([[1, 2], [3, 4]], [])) # [1, 2, 3, 4]

# 9. Complex numbers
print(sum([1+2j, 3+4j]))         # (4+6j)

# 10. Multiple iterables with start
print(sum([1, 2], sum([3, 4])))  # 10

6. pow()

Syntax: pow(base, exp, mod=None)
Description: Returns base raised to the power exp, optionally with modulus.

Examples:

python

# 1. Basic exponentiation
print(pow(2, 3))                 # 8

# 2. With modulus
print(pow(2, 3, 3))              # 2 (8 % 3 = 2)

# 3. Any number to power 0
print(pow(5, 0))                 # 1

# 4. Square root
print(pow(4, 0.5))               # 2.0

# 5. Negative exponent
print(pow(10, -2))               # 0.01

# 6. Large exponent with modulus
print(pow(2, 10, 100))           # 24

# 7. Floating point base
print(pow(2.5, 2))               # 6.25

# 8. Negative base
print(pow(-2, 3))                # -8

# 9. Fractional exponent
print(pow(8, 1/3))               # 2.0

# 10. Complex modulus operation
print(pow(7, 2, 5))              # 4 (49 % 5 = 4)

7. divmod()

Syntax: divmod(a, b)
Description: Returns a tuple containing the quotient and remainder when dividing a by b.

Examples:

python

# 1. Basic division
print(divmod(10, 3))             # (3, 1)

# 2. Even division
print(divmod(20, 4))             # (5, 0)

# 3. Floating point numbers
print(divmod(7.5, 2))            # (3.0, 1.5)

# 4. Negative numbers
print(divmod(-10, 3))            # (-4, 2)

# 5. Large numbers
print(divmod(100, 7))            # (14, 2)

# 6. With zero
print(divmod(0, 5))              # (0, 0)

# 7. Negative divisor
print(divmod(10, -3))            # (-4, -2)

# 8. Float divisor
print(divmod(10, 2.5))           # (4.0, 0.0)

# 9. Very large numbers
print(divmod(1000, 33))          # (30, 10)

# 10. Edge case with 1
print(divmod(1, 1))              # (1, 0)

8. eval()

Syntax: eval(expression, globals=None, locals=None)
Description: Evaluates a string as Python expression and returns the result.

Examples:

python

# 1. Basic arithmetic
print(eval("2 + 3 * 4"))         # 14

# 2. Function calls
print(eval("len('hello')"))      # 5

# 3. Using variables
x = 10
print(eval("x * 2"))             # 20

# 4. Built-in functions
print(eval("min(5, 2, 8)"))      # 2

# 5. List comprehension
print(eval("[i**2 for i in range(3)]"))  # [0, 1, 4]

# 6. Dictionary creation
print(eval("{'a': 1, 'b': 2}"))  # {'a': 1, 'b': 2}

# 7. Boolean expressions
print(eval("5 > 3 and 2 < 4"))   # True

# 8. String operations
print(eval("'hello' + ' ' + 'world'"))  # 'hello world'

# 9. Mathematical functions
print(eval("abs(-15)"))          # 15

# 10. Complex expression
print(eval("sum([x**2 for x in range(1, 4)])"))  # 14

# ⚠️ SECURITY WARNING: Never use eval() with untrusted input!
# eval() can execute arbitrary code and is a security risk.

Important Security Note: The eval() function should be used with extreme caution. It can execute any Python code, making it a significant security vulnerability when used with untrusted input. Always validate and sanitize input before using eval(), or consider safer alternatives like ast.literal_eval() for simple expressions.

Similar Posts

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

  • Functions as Parameters in Python

    Functions as Parameters in Python In Python, functions are first-class objects, which means they can be: Basic Concept When we pass a function as a parameter, we’re essentially allowing one function to use another function’s behavior. Simple Examples Example 1: Basic Function as Parameter python def greet(name): return f”Hello, {name}!” def farewell(name): return f”Goodbye, {name}!” def…

  • Function Returns Multiple Values in Python

    Function Returns Multiple Values in Python In Python, functions can return multiple values by separating them with commas. These values are returned as a tuple, but they can be unpacked into individual variables. Basic Syntax python def function_name(): return value1, value2, value3 # Calling and unpacking var1, var2, var3 = function_name() Simple Examples Example 1:…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

Leave a Reply

Your email address will not be published. Required fields are marked *