算数运算符 | 手把手教你入门Python之十九-阿里云开发者社区

 知识中心     |      2020-06-15 00:00:00

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《Python入门2020最新大课》,主讲人姜伟。

算数运算符

下面以a=10 ,b=20为例进行计算。

image.png
注意:混合运算时,优先级顺序为: * 高于 / % // 高于 + - ,为了避免歧义,建议使用 () 来处理理运算符优先级。 并且,不同类型的数字在进行混合运算时,整数将会转换成浮点数进行运算。

>>> 10 + 5.5 * 2
 21.0 
>>> (10 + 5.5) * 2 
31.0

算数运算符在字符串里的使用

如果是两个字符串做加法运算,会直接把这两个字符串拼接成一个字符串。

In [1]: str1 ='hello'
In [2]: str2 = 'world'
In [3]: str1+str2 
Out[3]: 'helloworld'
In [4]:
  • 如果是数字和字符串做加法运算,会直接报错。
In [1]: str1 = 'hello'
In [2]: a = 2
In [3]: a+str1 --------------------------------------------------------------------------TypeError                                 Traceback (most recent call last) <ipython-input-3-993727a2aa69> in <module> ----> 1 a+str1
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • 如果是数字和字符串做乘法运算,会将这个字符串重复多次。
In [4]: str1 = 'hello'
In [5]: str1*10 
Out[5]: 'hellohellohellohellohellohellohellohellohellohello'