How to make a number positive in Python

Learn how to make a negative number positive in Python using an example: add a minus sign before the number!

Making a Number Positive in Python

Python offers various ways to make a number positive. In this article, we'll look at how to make a number positive in Python with examples.

The simplest way to make a number positive is to use the built-in abs() function. This function takes a single argument and returns its absolute value. For instance, if we want to make the number -5 positive, we can use the following code:

positive_number = abs(-5)
print(positive_number)

The output of this code will be 5, since the absolute value of -5 is 5. The abs() function works with both integer and float numbers.

Another way to make a number positive is to use the math module. The math module provides a number of mathematical functions, including the fabs() function. This function takes a single argument and returns its absolute value, just like the abs() function. For example, if we want to make the number -6.7 positive, we can use the following code:

import math

positive_number = math.fabs(-6.7)
print(positive_number)

The output of this code will be 6.7, since the absolute value of -6.7 is 6.7. The fabs() function works with both integer and float numbers.

Finally, we can also make a number positive using the ternary operator. The ternary operator takes three arguments: a condition, a value to return if the condition is true, and a value to return if the condition is false. For example, if we want to make the number -7.2 positive, we can use the following code:

positive_number = -7.2 if -7.2 < 0 else 7.2
print(positive_number)

The output of this code will be 7.2, since the number is already positive. The ternary operator works with both integer and float numbers.

In conclusion, Python offers various ways to make a number positive. We can use the built-in abs() function, the math module's fabs() function, or the ternary operator to make a number positive. Each of these methods has pros and cons, and the choice depends on the specific requirements of the project.

Answers (0)