在Python中,`**`和`^`有什么区别?

huangapple go评论96阅读模式
英文:

What is the difference between ** and ^ in python

问题

在Python中,如果你想求一个整数的平方,你需要使用 ** 符号,但在Java中,你需要使用 ^ 符号;
但是,当我在我的代码中使用 ^ 符号时,Python并没有报错。
它只是给了我一些没有模式的东西,有人能解释一下在Python中使用 ^ 符号时会发生什么吗?
(图片见上方链接)

英文:

In python if you want to sqaure an int you have to put ** but in java you put ^;
But python didn't give me an error when I did ^ in my code

It just gave me something with no pattern can anyone explain what happens when you use ^ in python?
enter image description here

答案1

得分: 1

在Python中,**是指数运算符,而^是异或运算符(Python运算符

异或是两个数字的按位异或运算。换句话说,将每个数字表示为二进制,然后逐位对两个数字进行异或运算(当且仅当A和B不同的时候,A XOR B为真;如果它们相同,则为假。0表示假,1表示真)。

下面是一个计算5 XOR 3的示例:

5 ^ 3
101 = 5
011 = 3

从左到右:

1 ^ 0 -> 1
0 ^ 1 -> 1
1 ^ 1 -> 0
0 ^ 0 -> 0
  101
^ 011
-------
  110

因此,5^3=6

英文:

In python, ** is the exponentiation operator, and ^ is the XOR operator (python operators)

XOR is the bitwise XOR of the two numbers. In other words, write each number in binary, then take XOR of the two numbers one place at a time (A XOR B is true if A and B are different, and false if they're the same. 0 is false, 1 is true).

Here's an example computing 5 XOR 3:

5 ^ 3
101 = 5
011 = 3

from left to right:

1 ^ 0 -> 1
0 ^ 1 -> 1
1 ^ 1 -> 0
0 ^ 0 -> 0
  101
^ 011
-------
  110

so 5^3=6

huangapple
  • 本文由 发表于 2020年8月23日 11:53:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63543203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定