凡客网站登录,广告设计公司组织架构,地址二地址三2021变更,网站内页检测Python 中的条件语句是通过一条或多条语句的执行结果#xff08;True 或者 False#xff09;来决定执行的代码块。
它的一般格式为#xff1a;if...elif...else
if condition1: #条件1CodeBlock1 #代码块1
elif condition2:CodeBlock2
else:CodeBlock3
如果con…Python 中的条件语句是通过一条或多条语句的执行结果True 或者 False来决定执行的代码块。
它的一般格式为if...elif...else
if condition1: #条件1CodeBlock1 #代码块1
elif condition2:CodeBlock2
else:CodeBlock3
如果condition1成立那么执行CodeBlock1否则如果condition2成立则执行CodeBlock2否则执行CodeBlock3
下面是两个简单的例子
#输入成绩输出等级
ainput(请输入你的成绩)
afloat(a)
if a100:print(你的成绩等级为A)
elif a80 and a100:print(你的成绩等级为A)
elif a60 and a80:print(你的成绩等级为B)
elif a0 and a60:print(你的成绩不及格)
else:print(输入数据错误请重新输入) 但是我们要特别注意写条件时要注意条件之间是否有包含关系以及条件的顺序例如
#输入成绩输出等级
ainput(请输入你的成绩)
afloat(a)
if a60:print(你的成绩等级为C)
elif a80:print(你的成绩等级为B)
elif a90:print(你的成绩等级为A)
elif a100:print(你的成绩等级为A)
else:print(输入数据错误请重新输入)
输入80的时候结果如下 很明显这不是我们想要的结果
#数字猜谜游戏
numrandom.randint(1,100)
i0
while True:print(请输入一个0到100的数据, end)numinput input()numinputint(numinput)ii1if numinputnum:print(猜大了往小了猜)elif numinputnum:print(猜小了往大了猜)else:print(猜对啦)print(您一共猜了%d次%i)exit() match...case(在python3.10版本中增加类似C语言中的switch...case语句)
它的一般格式为
match subject:case pattern_1:action_1case pattern_2:action_2case pattern_3:action_3case _:action_wildcard
case _: 类似于 C 和 Java 中的 default:当其他 case 都无法匹配时匹配这条保证永远会匹配成功。
一个例子如下
def http_error(status):match status:case 400:return Bad requestcase 404:return Not foundcase 418:return Im a teapotcase _:return Somethings wrong with the internetmystatus400
print(http_error(400))
结果为
Bad request
一个 case 也可以设置多个匹配条件条件使用 隔开例如
...case 401|403|404:return Not allowed