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

  • AttributeError: ‘NoneType’ Error in Python re

    AttributeError: ‘NoneType’ Error in Python re This error occurs when you try to call match object methods on None instead of an actual match object. It’s one of the most common errors when working with Python’s regex module. Why This Happens: The re.search(), re.match(), and re.fullmatch() functions return: When you try to call methods like .group(), .start(), or .span() on None, you get this error. Example That Causes…

  • install Python, idle, Install pycharm

    Step 1: Download Python Step 2: Install Python Windows macOS Linux (Debian/Ubuntu) Open Terminal and run: bash Copy Download sudo apt update && sudo apt install python3 python3-pip For Fedora/CentOS: bash Copy Download sudo dnf install python3 python3-pip Step 3: Verify Installation Open Command Prompt (Windows) or Terminal (macOS/Linux) and run: bash Copy Download python3 –version # Should show…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

Leave a Reply

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