Skip to main content

How to find the absolute value of a number in Python

How to find the absolute value of a number in Python.

The absolute value of a number in Python can be found using the built-in abs() function. The absolute value of a number is the positive value of the number, regardless of its sign.

Here is a step-by-step tutorial on how to find the absolute value of a number in Python:

Step 1: Declare a variable and assign a number to it.

number = -5

In this example, we have assigned the number -5 to the variable number. You can replace this with any number of your choice.

Step 2: Use the abs() function to find the absolute value of the number.

absolute_value = abs(number)

The abs() function takes a number as an argument and returns its absolute value. In this example, we are passing the variable number as an argument to the abs() function and assigning the result to the variable absolute_value.

Step 3: Print the absolute value of the number.

print("The absolute value of", number, "is", absolute_value)

We use the print() function to display the absolute value of the number. The output will be in the format: "The absolute value of -5 is 5".

Here is the complete code:

number = -5
absolute_value = abs(number)
print("The absolute value of", number, "is", absolute_value)

Output:

The absolute value of -5 is 5

Additional Examples

Let's look at a few more code examples to find the absolute value of a number in different scenarios:

Example 1: Using the abs() function directly

absolute_value = abs(-10)
print("The absolute value is", absolute_value)

Output:

The absolute value is 10

Example 2: Using the absolute value of a variable in calculations

x = 7
y = -3
result = abs(x) + abs(y)
print("The sum of the absolute values is", result)

In this example, we find the absolute value of both x and y and then calculate their sum. The output will be: "The sum of the absolute values is 10".

Example 3: Finding the absolute value of a floating-point number

float_num = -3.14
abs_float = abs(float_num)
print("The absolute value of", float_num, "is", abs_float)

Output:

The absolute value of -3.14 is 3.14

These examples demonstrate different ways to find the absolute value of a number in Python using the abs() function.