How To Get Only Positive Value In Python

If you are working with numbers in Python, you may encounter situations where you want to get only a positive value from a calculation.

This could be useful, for example, for calculating absolute differences between two numbers or working with distance and other physical quantities that are always positive. In this tutorial, we will go over three methods to get only a positive value in Python using built-in functions and conditional expressions. Let’s get started!

Step 1: Use the built-in abs() function

Python has a built-in function called abs() that returns the absolute value of a number. If the number is positive, its absolute value is the same, and if the number is negative, its absolute value is the same number without the negative sign.

Here’s an example of using the abs() function:

Output:

8

This method is practical and straightforward when you need to get a single number’s positive counterpart quickly.

Step 2: Use a custom-built function

In some cases, you may want to create a custom function for turning negative numbers into positive ones. This method is particularly useful if you need to perform additional checks or transformations to the input data. Here’s an example of a custom function that returns a positive value:

Output:

12

This custom function checks if the number is less than 0 and multiplies it by -1 if it is, effectively turning it into its positive counterpart.

Step 3: Use list comprehension for multiple numbers

If you have a list of numbers and want to return a new list containing only the positive values, you can use list comprehension in combination with the abs() function or your custom function. Here’s an example for both:

Using abs() function:

Output:

[3, 5, 2, 8, 7, 10]

Using custom to_positive function:

Output:

[3, 5, 2, 8, 7, 10]

Both methods work similarly; you loop through the list of numbers and apply the function to each number to get a new list containing only positive values.

Full code:

Conclusion

In this tutorial, we have covered three methods for getting positive values in Python: using the built-in abs() function, creating a custom function, and using list comprehension for multiple values. Choose the approach that best suits your needs and remember to use these techniques to enhance your Python coding experience.