1.下列的值在作为布尔表达式时会被解释器看作为假
False None 0 " " ( ) [ ] { }
其他的一切都被解释为真,包括特殊值True
2.bool函数可以用来(和List,str以及tuple一样)转换其他值
>>> bool('I think, therefore I am')
True
>>> bool(42)
True
>>> bool('')
False
>>> bool(0)
False
尽管[ ]和“ ”都是假值,但他们本身却并不相等(也就是说[ ] != " ")
3.
Python中的比较运算符 |
表达式 |
描述 |
x == y |
x 等于 y |
x < y |
x 小于 y |
x > y |
x 大于 y |
x >= y |
x 大于等于 y |
x <= y |
x 小于等于 y |
x != y |
x 不等于 y |
x is y |
x 和 y 是同一个对象 |
x is not y |
x 和 y 是不同的对象 |
x in y |
x 是 y 容器(例如,序列)的成员 |
x not in y |
x 不是 y 容器的成员 |
4.相等运算符
>>> 'foo' == 'fool'
False
>>> 'foo' == 'foo'
True
5. is :同一性运算符
>>> x = y = [1,2,3]
>>> x is z #尽管他们的值相等,但还是两个不同的列表
使用==运算符来判定两个对象是否相等,使用is判定两者是否等同(同一个对象)
6. in :成员资格运算符
name = input('What is your name? ')
print('Your name contains the letter "s".')
print('Your name does not contains the letter "s".')
7. 字符串与序列比较
字符串可以按照字母顺序排列进行比较
>>> "alph" < "beta"
其他的序列也可以同同样的方式进行比较,不过比较的不是字符而是其他类型的元素
>>> [1,2] < [2,1]
如果一个序列包含其他序列元素,比较规则也同样适用于序列元素
>>> [2,[1,4]] < [2,[1,5]]
8.布尔运算符
number = int(input('Enter a number between 1 and 10 : '))
if number <= 10 and number >= 1 :
and , or , not 都是布尔运算符,存在短路逻辑。
name = input('Please enter your name : ') or '' #如果input语句的返回值为真,那么它就会赋给name,否则将默认的''赋值给name
name = input('Please enter your name : ') or '' #如果input语句的返回值为真,那么它就会赋给name,否则将默认的''赋值给name