一、控制结构Control Structures
1.条件分支 Conditional Branching
if boolean_expression1:
suite1
elif boolean_expression2:
suite2
...
elif boolean_expressionN:
suiteN
else:
else_suite
或者
expression1 if boolean_expression elseexpression2
2.while循环
while boolean_expression:
while_suite
else:
else_suite
3.for循环
for expression in iterable:
for_suite
else:
else_suite
while循环和for循环的else从句都是可选的,要特别注意的是只有while或for正常结束之后else从句才会被执行,如果有break或return语句执行,else从句是不会被执行的,两个循环应用示例(功能一致):
def list_find(lst, target): index = 0 while index < len(lst): if lst[index] == target: break index += 1 else: index = -1 return index |
def list_find(lst, target): for index, x in enumerate(lst): if x == target: break else: index = -1 return index
|
二、异常处理Exception Handling
1. 捕捉和引发异常Catching and Raising Exceptions
语法结构如下:
try: try_suite except exception_group1 as variable1: except_suite1 ... except exception_groupN as variableN: except_suiteN else: else_suite finally: finally_suite |
如果try_suite中引发一个异常,它会轮流在except从句中和exception_group匹配,如果引发的异常是exception_group的子类或与之类型相同,相应except从句将会被执行。
实践1:在try…excep