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

前端 未结 10 1027
小蘑菇
小蘑菇 2020-12-30 18:36

What is the difference between the following codes?

code1:

var=2**2*3

code2:

var2         


        
10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 19:07

    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.

提交回复
热议问题