四、控制结构和函数Control Structures and Functions

本文详细介绍了Python中的控制结构,包括条件分支、while和for循环,以及异常处理机制,如捕捉和引发异常。此外,还讨论了如何创建自定义函数,包括函数命名、文档字符串、参数处理和断言等重要概念。
摘要由CSDN通过智能技术生成

一、控制结构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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值