目录
if_else
"""
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
它通过逐个计算表达式,直到发现一个为真(有关真和假的定义,请参见布尔运算一节),
来选择其中一个套件;然后执行该套件(不执行或计算if语句的其他部分)。
如果所有表达式都为false,则执行else子句的套件(如果存在)。
The true value of the bool type. Assignments to True are illegal and raise a SyntaxError.
"""
condition = True
if condition:
print("Code block to execute")
else:
print("Code executed when the condition is false")
Code block to execute
布尔运算
概述
"""
在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为false:false、None、所有类型的数字零,
以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集)。
所有其他值都被解释为true。用户定义的对象可以通过提供一个_bool__;()方法自定义其真值。
如果运算符的参数为false,则运算符不会产生True,否则为false。
表达式x和y首先计算x;如果x为false,则返回其值;否则,计算y并返回结果值。
表达式x或y首先计算x;如果x为真,则返回其值;否则,计算y并返回结果值。
请注意,and和or都不限制返回的值和类型为False和True,而是返回最后一个经过计算的参数。
这有时很有用,例如,如果s是一个字符串,如果它是空的,则应该用默认值替换它,则表达式s或 'foo'会生成所需的值。
因为不必创建新值,它会返回一个boolean值,无论其参数的类型如何
(例如,not 'foo'生成False,而不是'')
"""
比较运算
"""
比较运算
==
def __eq__(self, x: object) -> bool
>
def __gt__(self, x: int) -> bool
<
def __lt__(self, x: int) -> bool
>=
def __ge__(self, x: int) -> bool
<=
def __le__(self, x: int) -> bool
!=
def __ne__(self, x: object) -> bool
"""
print("a == b : ", a == b)
print("a > b : ", a > b)
print("a < b : ", a < b)
print("a >= b : ", a >= b)
print("a <= b : ", a <= b)
print("a != b : ", a != b)
a == b : True
a > b : False
a < b : False
a >= b : True
a <= b : True
a != b : False
逻辑运算
"""
逻辑运算符
and
and_test ::= not_test | and_test "and" not_test
True and True -> True
or
or_test ::= and_test | or_test "or" and_test
True or False -> True
not
not_test ::= comparison | "not" not_test
not True -> False
"""
print("and : ", a == b and a >= b)
print("or : ", a == b or a > b)
print("not : ", not (a and b))
and : True
or : True
not : False
成员运算
"""
成员运算符
in
在指定序列中寻找指定对象,匹配成功则返回True,失败返回False
not in
运算符not in被定义为具有in的反真值。
"""
print("in : ", 1 in list_a)
print("not in : ", 2 not in list_a)
in : False
not in : False
身份运算
"""
身份运算符
is
判断两个标识是不是引用自一个对象
not is
判断两个标识是不是引用自不同对象
"""
print("T_Name : ", T_Name, "\nE_Name : ", E_name, "\nE_Name : ", F_name)
print("E is T : ", E_name is T_Name)
print("F is T : ", F_name is T_Name)
T_Name : relievedCy
E_Name : relievedCy
E_Name : relievedCy
E is T : False
F is T : True
*以上内容仅供参考