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

5 comments

  • comment by Tyler 13 Sep 07

    Thanks – that helped me out today.

  • comment by Rafael 26 Sep 08

    Thanks, definately good to know!

  • comment by Mo 26 Feb 09

    Hi, I left a program running for a while, expecting it to be done in a day or two. I wanted to generate a dictionary file of every possible combo of characters in an array (with alphanumeric content – uppercase and lowercase and numbers) I’ll have to re start it now! Thanks for the tip!

  • comment by TK 20 May 09

    Thanks, this definitely helps in my python knowledge, especially being a beginner :)

  • comment by Mark 9 Feb 10

    Thanks, that was a big help

Post a comment


Thanks for commenting. Please remember to be nice to others and keep your comment relevant to the discussion. I reserve the right to remove comments that don't meet these simple guidelines.