What's the difference between "2*2" and "2**2" in Python?

PythonSyntax

Python Problem Overview


What is the difference between the following codes?

code1:

var=2**2*3

code2:

var2=2*2*3

I see no difference. This raises the following question.

Why is the code1 used if we can use code2?

Python Solutions


Solution 1 - Python

Try:

2**3*2

and

2*3*2

to see the difference.

** is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.

Solution 2 - Python

Double stars (**) are exponentiation. So "2 times 2" and "2 to the power 2" are the same. Change the numbers and you'll see a difference.

Solution 3 - Python

  2**2 means 2 squared (2^2)
  2*2 mean 2 times 2 (2x2)

In this case they happen to have the same value, but...

  3**3*4 != 3*3*4

Solution 4 - Python

For visual learners.........................

enter image description here

Solution 5 - Python

To specifically answer your question Why is the code1 used if we can use code2? I might suggest that the programmer was thinking in a mathematically broader sense. Specifically, perhaps the broader equation is a power equation, and the fact that both first numbers are "2" is more coincidence than mathematical reality. I'd want to make sure that the broader context of the code supports it being

var = x * x * y
in all cases, rather than in this specific case alone. This could get you in big trouble if x is anything but 2.

Solution 6 - Python

2**2 = 2 power-of 2

2*2 = 2 times 2

Solution 7 - Python

The ** operator in Python is really "power;" that is, 2**3 = 8.

Solution 8 - Python

The top one is a "power" operator, so in this case it is the same as 2 * 2 equal to is 2 to the power of 2. If you put a 3 in the middle position, you will see a difference.

Solution 9 - Python

A double asterisk means to the power of. A single asterisk means multiplied by. 22 is the same as 2x2 which is why both answers came out as 4.

Solution 10 - Python

Power has more precedence than multiply, so:

2**2*3 = (2^2)*3
2*2*3 = 2*2*3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLéo Léopold Hertz 준영View Question on Stackoverflow
Solution 1 - PythonOscarRyzView Answer on Stackoverflow
Solution 2 - PythoneduffyView Answer on Stackoverflow
Solution 3 - PythonJiaaroView Answer on Stackoverflow
Solution 4 - PythonMohammed HView Answer on Stackoverflow
Solution 5 - PythonJohnMettaView Answer on Stackoverflow
Solution 6 - PythonJames BrooksView Answer on Stackoverflow
Solution 7 - PythonravuyaView Answer on Stackoverflow
Solution 8 - PythonGreg ReynoldsView Answer on Stackoverflow
Solution 9 - PythonAndrew MarshView Answer on Stackoverflow
Solution 10 - PythonvtlinhView Answer on Stackoverflow