一、基本运算符

Python运算符多数与C/C++/Java类似,但有少数不一样。
“/”表示求商,“//”求商的整数部分。11 / 2 = 5.500000, 11 // 2 = 5
”表示求幂。2 5 = 32

例1

a = 10
b = 3

x = a / b
y = a // b
z = a**b
print x,y,z

c = float(b)
m = a / c
n = a // c

运行结果:

3 3 1000
3.33333333333 3.0

二、成员运算符in和not in

in : 如果在指定的序列中找到值返回 True,否则返回 False
not in : 如果在指定的序列中没有找到值返回 True,否则返回 False

例2

a = 1
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
print "a is in the list"
else:
print "a is not in the list"

if ( b not in list ):
print "b is not in the list"
else:
print "b is in the list"

运行结果:

a is in the list
b is not in the list

三、身份运算符is和is not

is : 判断两个标识符是不是引用自一个对象
is not : 判断两个标识符是不是引用自不同的对象

例3

a = 20
b = 20

if ( a is b ):
print "a and b is the same object"
else:
print "a and b is not the same object"

if ( a is not b ):
print "a and b is not the same object"
else:
print "a and b is the same object"

b = 30
if ( a is b ):
print "a and b is the same object"
else:
print "a and b is not the same object"

运行结果:

a and b is the same object
a and b is the same object
a and b is not the

is与==的区别
is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等

例4 (以下代码位于Python交互式环境)

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

说明,b =a[:],这里冒号前面和后面都没有数字,表示取a的第一个元素到最后一个元素,放到另一个对象b里。所以b与a里的数据相同,但不是同一个对象。

四、运算符优先级

运算符

描述

()

括号(最高优先级)

**

指数

~ + -

按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)

  • / % //

乘,除,取模和取整除

  • -

加法减法

<<

右移,左移运算符

&

位 ‘AND’

^

位运算符

<= < > >=

比较运算符

<> == !=

等于运算符

= %= /= //= -= += = *=

赋值运算符

is, is not

身份运算符

in, not in

成员运算符

not, or, and

逻辑运算符


更多内容请关注微信公众号

小朋友学Python(12):运算符_运算符