How To Use abs() Function In Python With Examples

In Python, the `abs()` function is used to return the absolute value of a given number. The absolute value of a number is its distance from zero, regardless of whether it is positive or negative. In this article, I will tell you how to use the python abs() function with examples.

1. Python abs Function Definition.

  1. The `abs()` function in Python is a built-in function that returns the absolute value of a given number.
  2. The syntax for the `abs()` function is as follows:
    abs(num)
  3. The parameter `num` is the number whose absolute value is to be returned.
  4. If the given number is a complex number, the `abs()` function returns its magnitude.

2. Python abs Function Examples.

  1. Here are some common examples of using the `abs()` function in Python.
    Example 1:
    ```python
    num = -10
    abs_num = abs(num)
    print("Absolute value of", num, "is", abs_num)
    ```
    Output:
    ```
    Absolute value of -10 is 10
    ```
    In this example, we assign the value `-10` to the variable `num`. We then use the `abs()` function to get the absolute value of `num`, which is `10`.
    
    Example 2:
    ```python
    a = -5
    b = 10
    c = -15
    abs_sum = abs(a) + abs(b) + abs(c)
    print("Absolute sum of", a, "+", b, "+", c, "is", abs_sum)
    ```
    Output:
    ```
    Absolute sum of -5 + 10 + -15 is 30
    ```
    In this example, we have three variables `a`, `b`, and `c` with different values. We use the `abs()` function to get the absolute value of each variable and then add them together to get the absolute sum.
    
    Example 3:
    ```python
    num_list = [-2, 4, -6, 8, -10]
    abs_list = [abs(num) for num in num_list]
    print("Absolute values of", num_list, "are", abs_list)
    ```
    Output:
    ```
    Absolute values of [-2, 4, -6, 8, -10] are [2, 4, 6, 8, 10]
    ```
    In this example, we have a list of numbers `num_list`. We use a list comprehension to apply the `abs()` function to each number in the list and create a new list `abs_list` with the absolute values of the original numbers.
  2. Below is a complex number example using the python abs function.
    >>> num = 3 + 4j
    >>>
    >>> abs_num = abs(num)
    >>>
    >>> print("Absolute value of", num, "is", abs_num)
    Absolute value of (3+4j) is 5.0 
    
    # this is because √(3²+4²) = 5

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.