June 20th, 2013, 11:33 AM
Why doesn't the '**' operator return a positive value
I have recently started learning python from C++ and its been great! However I ran into a bug which was a bit annoying but I soon found out what it was. When I was using comparative operators for conditional statements, I realised that the '**' operator returns a negative value when I write an equation like this [negative number]**2. I don't understand this because surely it would return a postive number as it is doing say -5 * -5 which would return 25? Is there any other way to make multiply a base to the power of x to make it return a positive value in the given circumstance? Thank you!
June 20th, 2013, 12:34 PM
It has to do with python's operator precedence.
x = (-5) ** 2 sets x to 25
x = -5 ** 2 sets x to -25
This is because, without the parenthesis, it will evaluate 5 ** 2 first and then put the - sign on the result and hence you get -25.
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
June 20th, 2013, 12:54 PM
Thank you, this makes sense now!
Originally Posted by Scorpions4ever
June 20th, 2013, 05:43 PM
This works too ...
a = -5
x = a**2
print(x) # 25
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25