问题
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,
- 2^2 = 10
- ^10
= 00
= 0
- ^10
- 3^2 = 11
- ^10
= 01
= 1
- ^10
来源:https://stackoverflow.com/questions/48938847/why-does-python-use-for-exponentiation-instead-of-the-operator