编写“if”语句:
等于:a==b
不等于:a!=b
小于:a<b
小于或等于:a<=b
大于:a>b
大于或等于:a>=b
测试表达式:
a是97,b是55,因为97<55是假的,所以不能打印b。最后一句能打印a。
编写if语句
if语句的语法始终为:
if test_expression:
# statement(s) to be run
例如:
a是97,b是27。
97大于等于27,则真的,能打印a。
a是24,b是44。如果24<=0,则假的,不能打印a。打印b。
什么是“else”和“elif”语句?
if/else语句的语法始终为:
if test_expression:
# statement(s) to be run
else:
# statement(s) to be run
a是93,b是27。93>=27,则假的,不能打印a,只打印b。
if/elif语句的语法为:
if test_expression:
# statement(s) to be run
elif test_expression:
# statement(s) to be run
a是93,b是27。93>=27,则假的,不能打印“a is greater than or equal to b”这语句,只打印“a is equal to b”这语句。
结合使用if、elif和else语句:
if/elif语句的语法为:
if test_expression:
# statement(s) to be run
elif test_expression:
# statement(s) to be run
elif test_expression:
# statement(s) to be run
else:
# statement(s) to be run
使用嵌套条件逻辑:
嵌套条件逻辑的语法示例为:
if test_expression:
# statement(s) to be run
if test_expression:
# statements(s) to be run
else:
# statements(s) to be run
elif test_expression:
# statement(s) to be run
if test_expression:
# statements(s) to be run
else:
# statements(s) to be run
else:
# statement(s) to be run
a是16,b是25,c是27。16>25,则假的,不能打印。16=25,则假的,不能打印。打印了“a is less than b”。
什么是“and”和“or”运算符?
or运算符
使用or的布尔表达式具有以下语法:
sub-expression1 or sub-expression2
已确认了每一个字母,没有错误,还是运行失败了。
and运算符
使用or的布尔表达式具有以下语法:
sub-expression1 and sub-expression2
与上面的代码一模一样,就是把or改成and,但是运行会失败的。
and和or之间的差异
and的真值表:
subexpression1 | 运算符 | subexpression2 | 结果 |
Ture | and | Ture | Ture |
Ture | and | Falsh | Falsh |
Falsh | and | Ture | Falsh |
Falsh | and | Falsh | Falsh |
or的真值表:
subexpression1 | 运算符 | subexpression2 | 结果 |
Ture | or | Ture | Ture |
Ture | or | Falsh | Ture |
Falsh | or | Ture | Ture |
Falsh | or | Falsh | Falsh |