[分享] Python3基础Lesson7
784 查看
5 回复
 楼主 | 发布于 2018-04-03 | 只看楼主
分享到:

1. 异常捕获与产生

异常的捕获是通过try…except实现的,语法如下:

try:

try_suite

except exception_group1 as variable1:

except_suit1

except exception_group1N as variableN:

except_suitN

else:

else_suit

finally:

finally_suite

其中至少要包含一个except块,else和finally是可选的。在try块的suite正常执行完毕时,会执行else块的suite,如果发生异常就不执行。例:
d = [0, 1, 2, 3]
try:
    x = d[5]
except LookupError:
    print("Loopup error occurred")

输出结果:

Loopup error occurred


因为列表不含有d[5]项,所以报错并输出报错内容。


2. 关于*的一些用法

*本身也可以作为参数,用于表明在*后不再出现位置参数,但是关键字参数是允许的。例:

import math
def heron(a, b, c, *, units="meters"):
    s = (a + b + c)/2
    area = math.sqrt(s * (s-a) * (s-b) * (s-c))
    return "{0}{1}".format(area, units)
print(heron(25, 24, 7))
print(heron(25, 24, 7, units = "inches"))
print(heron(25, 24, 7, "inches"))

输出结果:

84.0meters

  File "/Users/user/PycharmProjects/untitled1/test.py", line 190, in <module>

84.0inches

    print(heron(25, 24, 7, "inches"))

TypeError: heron() takes 3 positional arguments but 4 were given

上面第三个调用中,我们尝试传递第四个位置参数,但是*不允许,并产生TypeError异常。


3. 也可以在参数中使用映射拆分操作符,通过这种方式创建的函数可以接受给定的任意数量的关键字参数。如:

def add_person_details(ssn, surname, **kwargs):
    print("SSN =", ssn)
    print("Surnname=", surname)
    for key in sorted(kwargs):
        print("{0}={1}".format(key, kwargs[key]))
add_person_details(483849, "Luther", forename = "Lexis", age =47)
输出结果:

SSN = 483849

Surnname= Luther

age=47

forename=Lexis


4. 断言assert语句

如下面函数,要求所有参数为非零值,将0作为编码错误。

def product(*args):
    result = 1
    for arg in args:
        result *= arg
    assert result, "0 argument"
   
return result
product(1, 2, 4, 0, 8, 3)

输出结果:

Traceback (most recent call last):

  File "/Users/user/PycharmProjects/untitled1/test.py", line 205, in <module>

    product(1, 2, 4, 0, 8, 3)

  File "/Users/user/PycharmProjects/untitled1/test.py", line 203, in product

    assert result, "0 argument"

AssertionError: 0 argument


NEXT。。。

(0 ) (0 )
回复 举报

回复于 2018-04-03 沙发

加油加油,不错的资料,谢谢分享
(0 )
评论 (0) 举报

回复于 2018-04-03 2#

感谢分享
(0 )
评论 (0) 举报

回复于 2018-04-03 3#

感谢分享
(0 )
评论 (0) 举报

回复于 2018-04-03 4#

多谢分享!!!
(0 )
评论 (0) 举报

回复于 2018-04-03 5#

感谢分享
(0 )
评论 (0) 举报
  • 发表回复
    0/3000





    举报

    请选择举报类别

    • 广告垃圾
    • 违规内容
    • 恶意灌水
    • 重复发帖

    全部板块

    返回顶部