Python算術運算符實例
假設變量 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