89DEVs

Python: How to make a negative number positive?

How to make a negative number positive in Python?

To make a negative number positive in Python, use the built-in abs() function. The abs() function returns the absolute value of a number. The absolute value is the distance from zero. # absolute value of number absolute value of -1 is 1 absolute value of 1 is 1 The absolute value of a number turns a negative number into a positive number. A already positive number, stays positive.

make a negative integer positive

To make a negative integer positive, use the abs() function as shown below. # make negative number positive myNumber = -2 myAbs = abs(myNumber) print(myAbs) In this example, the abs() function is used to turn a negative integer into a positive integer. First, the variable myNumber is defined and the negative integer -2 is assigned to it. Then, the abs() function is used on myNumber and the result is assigned to the myAbs variable. Finally, the myAbs variable is printed and the result is shown below. 2

make a negative float positive

The abs() function works for float values the same way as it works for integer. To make a negative float positive, use the abs() function as shown below. # make negative float positive myFloat = -2.2 myAbs = abs(myFloat) print(myAbs) In this example, first the variable myFloat is defined and the negative float value of -2.2 is assigned to it. Then, the abs() function is used and myFloat is passed as argument. The absolute value is calculated and a negative float turns into a positive float. The result is assigned to the variable myAbs. Finally, the result is printed as float value as shown below. 2.2

make a negative number positive using max()

An alternative approach is to use the max() function as shown below. There is some overhead using this alternative, so it is not recommended and estimated to be slower than using abs(). # make a negative number positive using max() myInt = -2 myPositiveInt = max(myInt, -myInt) print(myPositiveInt) In this example, the negative integer -2 is assigned to the variable myInt. Then, the max() function is used and the variable myInt is passed twice to it. The first argument is the unchanged integer and the second argument is a minus followed by the integer. The max() function returns the largest item that is passed to it. Therefore it returns always the positive number. So in this case the first argument equals to -2 and the second argument equals to 2. Because 2 is bigger than -2, the max() function returns 2. This approach uses the fact that a positive number is always bigger than a negative number and therefore max() will return always the positive number. Finally, the variable myPositiveInt is printed and the result is the positive integer 2 as shown below. 2

                
        

Summary


Click to jump to section