# Python基础教程 更复杂的条件＆断言

5.4.6 更复杂的条件

1. 比较运算符

x == y x 等于y

x

x > y x大于y

x >= y x大于或等于y

x

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的成员

 相等运算符

>>> "foo" == "foo"

True

>>> "foo" == "bar"

False

>>> "foo" = "foo"

SyntaxError: can't assign to literal

 is：相同运算符

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

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

>>> x == y

True

>>> x == z

True

>>> x is y

True

>>> x is z

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

 in：成员资格运算符

name = input('What is your name?')

if 's' in name:

print('Your name contains the letter "s".')

else:

print('Your name does not contain the letter "s".')

 字符串和序列的比较

>>> "alpha"

True

>>> " "

True

>>> ord(" ")

128585

>>> ord(" ")

128586

>>> chr(128584)

' '

>>> "a"

False

>>> "a".lower()

True

>>> 'FnOrD'.lower() == 'Fnord'.lower()

True

>>> [1, 2]

True

>>> [2, [1, 4]]

True

2. 布尔运算符

number = int(input('Enter a number between 1 and 10: '))

if number

if number >= 1:

print('Great!')

else:

print('Wrong!')

else:

print('Wrong!')

number = int(input('Enter a number between 1 and 10: '))

if number = 1:

print('Great!')

else:

print('Wrong!')

if ((cash > price) or customer_has_good_credit) and not out_of_stock:

give_goods()

5.4.7 断言

if语句有一个很有用的“亲戚”，其工作原理类似于下面的伪代码：

if not condition:

crash program

>>> age = 10

>>> assert 0

>>> age = -1

>>> assert 0

Traceback (most recent call last):

File "", line 1, in ?

AssertionError

>>> age = -1

>>> assert 0

Traceback (most recent call last):

File "", line 1, in ?

AssertionError: The age must be realistic

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20180913G0DEYP00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2022-05-22

2022-05-22

2022-05-22

2022-05-22

2022-05-22

2022-05-22

2018-07-02

2018-06-21

2018-03-23

2022-05-22

2022-05-22

2022-05-22