Why does Python `**` use for exponentiation instead of the `^` operator? [duplicate]

假如想象 提交于 2021-02-04 21:59:30

问题


Why is ^ not squaring in Python? I know exponentiation is ** instead, but what exactly is ^ and why wasn't that operator used instead?

For example 2^2=0, 3^2=1.


回答1:


The ^ operator was already used for bitwise xor.

>>> x = 42; format(x, '08b')
'00101010'
>>> y = 137; format(y, '08b')
'10001001'
>>> z = x ^ y; format(z, '08b')
'10100011'

That leaves the old Fortran-style ** operator for exponentiation.

>>> base = 5
>>> exp = 2
>>> base ** exp
25



回答2:


The "^" symbol in python is a bit-wise exclusive OR (XOR) operator. An OR gate is true if one of the inputs OR another is true. The XOR gate is true if and only if just a single input is true. 00 and 11 are false. 01 and 10 are true. The bit-wise XOR can be used to check how many bits differ.

For example,

  1. 2^2 = 10
    • ^10
      = 00
      = 0
  2. 3^2 = 11
    • ^10
      = 01
      = 1


来源:https://stackoverflow.com/questions/48938847/why-does-python-use-for-exponentiation-instead-of-the-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!