# Python 运算符

## 什么是运算符？

Python语言支持以下类型的运算符:
• 算术运算符
• 比较（关系）运算符
• 赋值运算符
• 逻辑运算符
• 位运算符
• 成员运算符
• 身份运算符
• 运算符优先级

## 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

## Python比较运算符

#!/usr/bin/python

a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c

c += a
print "Line 2 - Value of c is ", c

c *= a
print "Line 3 - Value of c is ", c

c /= a
print "Line 4 - Value of c is ", c

c  = 2
c %= a
print "Line 5 - Value of c is ", c

c **= a
print "Line 6 - Value of c is ", c

c //= a
print "Line 7 - Value of c is ", c

Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

## Python位运算符

#!/usr/bin/python

a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
c = 0

c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b;        # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c

c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c

c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

## Python逻辑运算符

Python语言支持逻辑运算符，以下假设变量a为10，变量b为20：

#!/usr/bin/python

a = 10
b = 20
c = 0

if ( a and b ):
print "Line 1 - a and b are true"
else:
print "Line 1 - Either a is not true or b is not true"

if ( a or b ):
print "Line 2 - Either a is true or b is true or both are true"
else:
print "Line 2 - Neither a is true nor b is true"

a = 0
if ( a and b ):
print "Line 3 - a and b are true"
else:
print "Line 3 - Either a is not true or b is not true"

if ( a or b ):
print "Line 4 - Either a is true or b is true or both are true"
else:
print "Line 4 - Neither a is true nor b is true"

if not( a and b ):
print "Line 5 - Either a is not true or b is  not true or both are not true"
else:
print "Line 5 - a and b are true"

Line 1 - a and b are true
Line 2 - Either a is true or b is true or both are true
Line 3 - Either a is not true or b is not true
Line 4 - Either a is true or b is true or both are true
Line 5 - Either a is not true or b is  not true or both are not true

12 篇文章15 人订阅

0 条评论