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

网友投稿 1180 2022-09-04

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

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

一、基本运算符

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

例1

a = 10b = 3x = a / by = a // bz = a**bprint x,y,z c = float(b)m = a / cn = a // c

运行结果:

3 3 10003.33333333333 3.0

二、成员运算符in和not in

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

例2

a = 1b = 20list = [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 listb is not in the list

三、身份运算符is和is not

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

例3

a = 20b = 20if ( 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 = 30if ( 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 objecta and b is the same objecta and b is not the

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

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

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

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

四、运算符优先级

运算符

描述

()

括号(最高优先级)

**

指数

~ + -

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

  • / % //

乘,除,取模和取整除

  • -

加法减法

<<

右移,左移运算符

&

位 ‘AND’

^

位运算符

<= < > >=

比较运算符

<> == !=

等于运算符

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

赋值运算符

is, is not

身份运算符

in, not in

成员运算符

not, or, and

逻辑运算符

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:小朋友学Python(11):变量类型
下一篇:缓存穿透,缓存击穿,缓存雪崩解决方案分析(缓存穿透 击穿 雪崩)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~