上一篇: 詳解4種類型轉換 | 手把手教你入門Python之十八 下一篇: 詳解兩種指派運算符的使用 | 手把手教你入門Python之二十 本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程 《Python入門2020最新大課》 ,主講人姜偉。
算數運算符
下面以a=10 ,b=20為例進行計算。

注意:混合運算時,優先級順序為: ** 高于 * / % // 高于 + - ,為了避免歧義,建議使用 () 來處理運算符優先級。 并且,不同類型的數字在進行混合運算時,整數将會轉換成浮點數進行運算。
>>> 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'