Python算术运算符示例

假设变量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

上一篇: Python基本运算符 下一篇: Python决策