Python算術運算子範例

2019-10-16 23:11:39
假設變數 a=10 和 變數b=20,然後:
操作符 描述 範例
將操作符的兩側數值增加(加法運算)
a + b = 30
左運算元減去右運算元
a – b = -10
操作符兩側資料相乘(乘法運算)
a * b = 200
操作符左側運算元除以右運算元
b / a = 2
左運算元除以右側運算元的餘數
b % a = 0
** 
執行指數(冪)計算
a**b 就是10 的20 次冪
// 地板除 - 除法不管運算元為何種數值型別,總是會捨去小數部分,返回數位序列中比真正的商小的最接近的數位 9//2 = 4 以及 9.0//2.0 = 4.0

範例

假設變數 a = 10和變數 b = 20,那麼 -
#!/usr/bin/python3

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.1
Line 5 - Value of c is  1
Line 6 - Value of c is  8
Line 7 - Value of c is  2