Python Mystery Powers

  • Posted by Mike Naberezny in Python

    Beginning Python programmers can be easily confused by the numeric operator for exponents. In many languages, the statement:

    print(2^2)
    

    Will return 4, or 2 raised to the power of 2. However, the ^ operator in Python has a completely different meaning. It actually returns the bitwise exclusive OR of the two numbers. For the example of 2^2, the number 0 will be returned instead of the expected 4.

    To express exponents in Python, use either:

    x = pow(a,b)
    x = a**b