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

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • ASCII ,Uni Code Related Functions in Python

    ASCII Code and Related Functions in Python ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numerical values to letters, digits, punctuation marks, and other characters. Here’s an explanation of ASCII and Python functions that work with it. ASCII Basics Python Functions for ASCII 1. ord() – Get ASCII value of a…

  • Python timedelta Explained

    Python timedelta Explained timedelta is a class in Python’s datetime module that represents a duration – the difference between two dates or times. It’s incredibly useful for date and time arithmetic. Importing timedelta python from datetime import timedelta, datetime, date Basic Syntax python timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Examples 1. Basic timedelta Creation python from datetime…

Leave a Reply

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