Python算術運算子範例

2019-10-16 23:08:01

假設變數a的值是10,變數b的值是21,則 -

運算子 描述 範例
+ 加法運算,將運算子兩邊的運算元增加。 a + b = 31
- 減法運算,將運算子左邊的運算元減去右邊的運算元。 a – b = -11
* 乘法運算,將運算子兩邊的運算元相乘 a * b = 210
/ 除法運算,用右運算元除左運算元 b / a = 2.1
% 模運算,用右運算元除數左運算元並返回餘數 b % a = 1
** 對運算子進行指數(冪)計算 a ** b,表示1021次冪
// 地板除 - 運算元的除法,其結果是刪除小數點後的商數。 但如果其中一個運算元為負數,則結果將被保留,即從零(向負無窮大)捨去 9//2 = 49.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0

範例

假設變數a的值是10,變數b的值是21,參考以下程式碼實現 -

#!/usr/bin/python3
#coding=utf-8

# save file : arithmetic_operators_example.py

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)

將上面程式碼儲存到檔案: arithmetic_operators_example.py 中,執行結果如下 -

F:\worksp\python>python arithmetic_operators_example.py
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.1
Line 5 - Value of c is  1
Line 6 - Value of c is  8
Line 7 - Value of c is  2