Python中的简单计算

(1)基本的加减乘除
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  1.6

2)除法总是会返回一个浮点数,想要返回整数,需要用“//”来表示(floor division),另外,可以用“%”进行取余操作

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2

3)幂运算可以使用“**”来进行

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

需要注意的是,

>>> -3**2 #it will be interpretedas -(3**2)

-9

如果需要得到正确的结果,需要下面的写法

>>> (-3)**2

9

 

除了floatint类型的数据之外,还支持其他类型的数字,例如DecimalFraction,当然python也支持复杂的数据格式,一般都是以j或者J作为后缀,例如3+5j