条件、循环和其余语句学习1

一、bool值shell

假:False、None、全部的数字类型0(包含浮点型、长整型和其余类型)、''、[]、()等空的序列都为假,空的字典{}也是假函数

真:除去假的都当作真spa

bool函数能够将其余类型值转换成bool值对象

>>> bool(0.00)
False
>>> bool(1.23)
Trueblog

>>> bool('string')
True内存

二、条件比较运算符,比较运算符不适用不一样类型(不一样类型不可作比较会报错)input

 

三、相等运算符==,判断左右两边内容是否一致,包括值和类型string

 

>>> x = y =[1,2,3]
>>> z = [1,2,3]io

>>> x == y
True
>>> z == x
Trueast

四、is 同一性运算符 判断的是变量指向的内容和位置是否一致,就是判断左右两边是不是同一个对象

 

>>> x = y =[1,2,3]
>>> z = [1,2,3] ###z是一个跟x和y指向的位置的内容相同,可是内存中的位置不一样 因此z is x返回False
>>> x is y
True
>>> z is x
False

 

实例:

>>> x = [1,2,3]
>>> y = [2,4]
>>> x is not y
True
>>> del x[2]
>>> y[1] = 1
>>> y.reverse()
>>> x == y  ###判断同类型变量的内容相等性
True
>>> x is y ###判断变量的同一性
False

五、bool运算符 and、or、not ,布尔运算符也成为条件运算符,是短逻辑运算(只有在须要求值时才进行运算

 

>>> a = 1
>>> b = 2
>>> a and b ###由于是and运算因此若是a是true 则须要进行b的运算,而后返回b的值;若是a是false,则返回a的值,不会再去运算b的值
2

>>> a = 0
>>> a and b ####由于是and运算,若是a是false,则返回a的值,不会再去运算b的值
0

### 若是是OR运算的话,若是第一个条件的值为true,则返回第一个条件的值,第二个条件不会运算;若是第一为false,则运行第二个的值,返回第二个的值

>>> name = input('please enter your name:') or '<unknown>'
please enter your name: ###没有输入值,直接回车,返回'<unknown>'给name
>>> name
'<unknown>'

###内置条件语句 a if b else c:b为真返回a ,不然返回b

>>> input('please enter your name:') if input('please enter your name:') else '<unknown>'
please enter your name:
'<unknown>'

 

not 是对条件的bool值取反

>>> a = 0

 

>>> not a
True

六、断言assert,条件成立则不返回,条件不成立则返回AssertError,提示内容能够本身指定

 

>>> a =10
>>> assert a<=10 and a>0

>>> assert 0<a<=10,'the age is listic'####条件不成立时返回本身的指定提示'the age is listic'
Traceback (most recent call last):
File "<pyshell#183>", line 1, in <module>
assert 0<a<=10,'the age is listic'
AssertionError: the age is listic

相关文章
相关标签/搜索