close

How to convert positive numbers to negative in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert positive numbers to negative in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert positive numbers to negative in Python?

  1. How to convert positive numbers to negative in Python?

    This may not matter much at all, but if this code is in a gameloop or anything else then the overhead of the function call would could add up.

  2. convert positive numbers to negative in Python

    This may not matter much at all, but if this code is in a gameloop or anything else then the overhead of the function call would could add up.

Method 1

If you want to force a number to negative, regardless of whether it’s initially positive or negative, you can use:

    -abs(n)

Note that 0 will remain 0.

Method 2

-abs(n) is a really good answer by Tom Karzes earlier because it works whether you know the number is negative or not.

If you know the number is a positive one though you can avoid the overhead of a function call by just doing subtraction:

0 - n 

This may not matter much at all, but if this code is in a gameloop or anything else then the overhead of the function call would could add up.

>>> timeit.timeit("-abs(40)")
0.08589089001179673
>>> timeit.timeit("0 - 40")
0.01394932100083679

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read