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

1、bool值

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

真:除去假的都当做真

bool函数可以将其他类型值转换成bool值

>>> bool(0.00)
False
>>> bool(1.23)
True

>>> bool('string')
True

2、条件比较运算符,比较运算符不适用不同类型(不同类型不可做比较会报错)

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

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

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

4、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

5、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

6、断言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

猜你喜欢

转载自www.cnblogs.com/t-ae/p/10849666.html
今日推荐