0

I have a variable of type int, it's Python, so it can be positive and negative. Now, I want to make another variable have the same sign as the first variable1. It's easy to do this by using an if statement and then assign -1 or +1 to a variable and multiply every variable I want to have this sign by the -1 or +1. But then I thought maybe there is another way to do this (e.g. a built-in function). Is there something like "sign = getsignbit(value)"?

edit: Solved! math.copysign did the thing, cmp(x,0) works too, but I don't only want -1, 0 or 1, but also turn a 5 into -5.

1
  • sign = lambda x: math.copysign(1, x) looks good Commented Nov 1, 2013 at 20:57

2 Answers 2

3

There's no built in sign function (see this answer for some explanation: Why doesn't Python have a sign function? ), but math.copysign might be useful to you. http://docs.python.org/2/library/math.html#math.copysign

Sign up to request clarification or add additional context in comments.

Comments

3

I don't think there is a built-in function, but you can roll your own easily enough:

def the_sign(num): return cmp(num, 0) 

2 Comments

I'm using Python 2.7, it works both but I like math.copysign better. I still gave a +1 though ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.