How to convert a positive number into a Negative in Python

In this tutorial, I will teach you to convert positive numbers into negatives in Python. There are basically four ways to implement this thing. However, I will show the method which I use mostly to convert positive numbers to negative numbers.

Nowadays, Developers need to implement this type of mechanism into various applications especially gaming apps.

In Python, how do you turn a positive number into a negative number?

Let’s begin with the first method,

This method is the simplest method and developers use frequently to implement in the program.

for i in range(1,4):
    print(-abs(i))

Output:

-1
-2
-3

In this method, I have used -abs() method which converts 1 to 4 numbers into negative integers ( as you can see in output).

Second method,

This is also a well-known way but not used much but anyway let’s look at it

for i in range(1,10):
    i='-' + str(i).strip()
    print(i)

Output:

-1
-2
-3
-4
-5
-6
-7
-8
-9

Here, I have used strip() keyword to join converted (int to string) number to “-” sign.

Third method,

This method is logically good to implement

list=[1,2,3,4]
for i in list:
    neg = i * (-1)
    print(neg)

Output:

-1
-2
-3
-4

Here, just simply I have multiplied the list of numbers with -1 so, it returns negative numbers at the end.

Fourth method,

This method is similar to the third one,

import random
array1 = []
arrayLength = 4
for i in range(arrayLength):
   array1.append((random.randint(0, arrayLength)*-1))
print(array1)

Output:

[-4, 0, -3, -3]

However, this method is also good as it returns random values with a list of negative numbers. so, sometimes developers need to use such type of mechanism while developing applications/websites.

Leave a Reply

Your email address will not be published.