Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
June 20th, 2013, 12:33 PM
 jonnimeggi
Registered User

Join Date: Jun 2013
Posts: 4
Time spent in forums: 1 h 4 m 32 sec
Reputation Power: 0
Why doesn't the '**' operator return a positive value

Hi everybody

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!

#2
June 20th, 2013, 01:34 PM
 Scorpions4ever
Banned ;)

Join Date: Nov 2001
Location: Woodland Hills, Los Angeles County, California, USA
Posts: 9,539
Time spent in forums: 2 Months 3 Days 9 h 6 m 17 sec
Reputation Power: 4106
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

#3
June 20th, 2013, 01:54 PM
 jonnimeggi
Registered User

Join Date: Jun 2013
Posts: 4
Time spent in forums: 1 h 4 m 32 sec
Reputation Power: 0
Quote:
 Originally Posted by Scorpions4ever 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.

Thank you, this makes sense now!

#4
June 20th, 2013, 06:43 PM
 Dietrich
Contributing User

Join Date: Feb 2005
Posts: 576
Time spent in forums: 5 Days 4 h 58 m
Reputation Power: 63
This works too ...
Code:
```a = -5
x = a**2
print(x)  # 25```
__________________
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Why doesn't the '**' operator return a positive value