0

I am trying to calculate 5^2 in Python and the result is coming out as 7. I am attaching a snippet of my code. Any idea of what's happening?

I've tried:

math.pow(a,b)
a**b
eval(str(x))

I am receiving the same result of 7 for each of them. I have also imported math.

This is my current code that I am using:

question = ["5^2"]
def checkExponent(self, question):
     for i in range(len(question)):
          if question[i] == "^":
               return(math.pow(int(question[i-1]), int(question[i+1])))

def calculate(self):
     temp = 0
     for i in range(len(self.problemArray)):
          if self.checkExponent(self.problemArray[i]) == "":
               temp = self.checkExponent(self.problemArray[i])
          else:
               temp = eval(str(self.problemArray[i]))
          self.answerArray.append(temp)
          temp = 0

I was originally using:

def calculate(self):
     temp = 0
     for i in range(len(self.problemArray)):
          temp = eval(str(self.problemArray[i]))
          self.answerArray.append(temp)
          temp = 0
poppy14s
  • 37
  • 11
  • 2
    That is XOR bitwise operator. – jupiterbjy Jun 30 '20 at 14:55
  • 1
    Please update your question with your full code. You seem to have posted a few methods from a class but there are no examples of calling these methods. – quamrana Jun 30 '20 at 14:56
  • 1
    Can't reproduce the issue. `checkExponent(None, question[0])` -> `25.0`. You need to provide a [mre]. **Edit**: Oh wait, is that a red herring? I missed the code where you call `eval`, i.e. `eval("5^2")` -> `7`. – wjandrea Jun 30 '20 at 14:59
  • 1
    Duplicates: [Python and Powers Math](https://stackoverflow.com/q/12043913/4518341), [How do I do exponentiation in python?](https://stackoverflow.com/q/30148740/4518341) – wjandrea Jun 30 '20 at 15:10

2 Answers2

4

^ is the bitwise XOR operator. If you eval() it then 5^2 becomes 0b101 xor 0b010 so 0b111 = 7.

Use a ** b, and avoid using eval.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
jupiterbjy
  • 2,882
  • 1
  • 10
  • 28
  • 1
    Okay, thank you. I changed the file with my problem in it from a "^" to a "**" and it does it properly now. – poppy14s Jun 30 '20 at 16:54
2

Python is filled with bunch of awesomeness for the programmers to use In order to calculate 5^2 simply write 5**2 I am not able to understand why you insist on using such a long code for such a simple operation. I accept that this is not the perfect answer for your question , though it is more optimised approach which will be beneficial for you