Python算術運算符示例
下表列出了所有Python語言支持的算術運算符。假設變量a持有10和變量b持有20,則:
運算符 | 描述 | 實例 |
---|---|---|
+ | 加法 - 對操作符的兩側加值 | a + b = 30 |
- | 減法 - 從左側操作數減去右側操作數 | a - b = -10 |
* | 乘法- 相乘運算符兩側的值 | a * b= 200 |
/ | 除 - 由右側操作數除以左側操作數 | b / a = 2 |
% | 模 - 由右側操作數和餘返回除以左側操作數 | b % = 0 |
** | 指數- 執行對操作指數(冪)的計算 | a**b = 10 冪為 20 |
// | 地板除 - 操作數的除法,其中結果是將小數點後的位數被除去的商。 | 9//2 = 4 而 9.0//2.0= 4.0 |
例子:
試試下麵的例子就明白了所有的Python編程語言提供了算術運算符:
#!/usr/bin/python a = 21 b = 10 c = 0 c = a + b print "Line 1 - Value of c is ", c c = a - b print "Line 2 - Value of c is ", c c = a * b print "Line 3 - Value of c is ", c c = a / b print "Line 4 - Value of c is ", c c = a % b print "Line 5 - Value of c is ", c a = 2 b = 3 c = a**b print "Line 6 - Value of c is ", c a = 10 b = 5 c = a//b print "Line 7 - Value of c is ", c
當執行上麵的程序,它會產生以下結果:
Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 Line 6 - Value of c is 8 Line 7 - Value of c is 2