Python 30 天:第 17 天 -- 异常处理

文章讲述了Python中如何使用try和except进行异常处理,以优雅地管理错误,防止程序崩溃。同时,介绍了使用*和**运算符对参数进行打包和解包,以及enumerate和zip函数在处理列表和字典时的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<< 第 16 天 || 第 18 天 >>

第 17 天 

异常处理

Python 使用tryexcept优雅地处理错误。优雅地退出(或优雅地处理)错误是一个简单的编程习惯用法——程序检测到严重的错误情况并因此以受控方式“优雅地退出”。通常程序会在终端或日志中打印一条描述性错误消息作为正常退出的一部分,这使我们的应用程序更加健壮。异常的原因通常是程序本身的外部原因。异常的示例可能是输入不正确、文件名错误、无法找到文件、IO 设备出现故障。优雅地处理错误可以防止我们的应用程序崩溃。

我们在上一节中介绍了不同的 Python错误类型。如果我们在我们的程序中使用tryexcept,那么它不会在这些块中引发错误。

try:
    code in this block if things go well
except:
    code in this block run if things go wrong

例子:

try:
    print(10 + '5')
except:
    print('Something went wrong')

在上面的示例中,第二个操作数是一个字符串。我们可以将其更改为 float 或 int 以将其与数字相加以使其工作。但是没有任何变化,第二个块,除了,将被执行。

例子:

try:
    name = input('Enter your name:')
    year_born = input('Year you were born:')
    age = 2019 - year_born
    print(f'You are {name}. And your age is {age}.')
except:
    print('Something went wrong')
Something went wrong

在上面的例子中,异常块会运行,我们并不知道到底是什么问题。为了分析问题,我们可以使用 except 的不同错误类型。

在下面的示例中,它将处理错误并告诉我们引发的错误类型。

try:
    name = input('Enter your name:')
    year_born = input('Year you were born:')
    age = 2019 - year_born
    print(f'You are {name}. And your age is {age}.')
except TypeError:
    print('Type error occured')
except ValueError:
    print('Value error occured')
except ZeroDivisionError:
    print('zero division error occured')

Enter your name:Asabeneh
Year you born:1920
Type error occured

 在上面的代码中,输出将是TypeError。现在,让我们添加一个额外的块:

try:
    name = input('Enter your name:')
    year_born = input('Year you born:')
    age = 2019 - int(year_born)
    print('You are {name}. And your age is {age}.')
except TypeError:
    print('Type error occur')
except ValueError:
    print('Value error occur')
except ZeroDivisionError:
    print('zero division error occur')
else:
    print('I usually run with the try block')
finally:
    print('I alway run.')
Enter your name:Asabeneh
Year you born:1920
You are Asabeneh. And your age is 99.
I usually run with the try block
I alway run.

它还将上面的代码缩短如下: 

try:
    name = input('Enter your name:')
    year_born = input('Year you born:')
    age = 2019 - int(year_born)
    print('You are {name}. And your age is {age}.')
except Exception as e:
    print(e)

在Python中打包和解包参数 

我们使用两个运算符:

  • * 对于元组
  • ** 对于字典

让我们以下面为例。它只接受参数,但我们有列表。我们可以解压列表并更改参数。

解包

解包清单

def sum_of_five_nums(a, b, c, d, e):
    return a + b + c + d + e

lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e'

当我们运行此代码时,它会引发错误,因为此函数将数字(而不是列表)作为参数。让我们解包/解构列表。

def sum_of_five_nums(a, b, c, d, e):
    return a + b + c + d + e

lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(*lst))  # 15

 我们还可以在需要开始和结束的范围内置函数中使用解包。

numbers = range(2, 7)  # normal call with separate arguments
print(list(numbers)) # [2, 3, 4, 5, 6]
args = [2, 7]
numbers = range(*args)  # call with arguments unpacked from a list
print(numbers)      # [2, 3, 4, 5,6]

 列表或元组也可以像这样解包:

countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
fin, sw, nor, *rest = countries
print(fin, sw, nor, rest)   # Finland Sweden Norway ['Denmark', 'Iceland']
numbers = [1, 2, 3, 4, 5, 6, 7]
one, *middle, last = numbers
print(one, middle, last)      #  1 [2, 3, 4, 5, 6] 7

解压字典 

def unpacking_person_info(name, country, city, age):
    return f'{name} lives in {country}, {city}. He is {age} year old.'
dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250}
print(unpacking_person_info(**dct)) # Asabeneh lives in Finland, Helsinki. He is 250 years old.

打包 

有时我们永远不知道需要将多少参数传递给 python 函数。我们可以使用 packing 方法来允许我们的函数接受无限数量或任意数量的参数。

打包清单

def sum_all(*args):
    s = 0
    for i in args:
        s += i
    return s
print(sum_all(1, 2, 3))             # 6
print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28

打包字典 

def packing_person_info(**kwargs):
    # check the type of kwargs and it is a dict type
    # print(type(kwargs))
	# Printing dictionary items
    for key in kwargs:
        print("{key} = {kwargs[key]}")
    return kwargs

print(packing_person_info(name="Asabeneh",
      country="Finland", city="Helsinki", age=250))

name = Asabeneh
country = Finland
city = Helsinki
age = 250
{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}

在Python中 传播

与在 JavaScript 中一样,在 Python 中传播也是可能的。让我们在下面的示例中检查一下:

lst_one = [1, 2, 3]
lst_two = [4, 5, 6, 7]
lst = [0, *list_one, *list_two]
print(lst)          # [0, 1, 2, 3, 4, 5, 6, 7]
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries)  # ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']

枚举 

如果我们对列表的索引感兴趣,我们使用enumerate内置函数来获取列表中每个项目的索引。

for index, item in enumerate([20, 30, 40]):
    print(index, item)
for index, i in enumerate(countries):
    print('hi')
    if i == 'Finland':
        print('The country {i} has been found at index {index}')
The country Finland has been found at index 1.

压缩

有时我们希望在遍历列表时合并列表。请参见下面的示例:

fruits = ['banana', 'orange', 'mango', 'lemon', 'lime']                    
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
fruits_and_veges = []
for f, v in zip(fruits, vegetables):
    fruits_and_veges.append({'fruit':f, 'veg':v})

print(fruits_and_veges)
[{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}, {'fruit': 'lime', 'veg': 'Carrot'}]

🌕你下定决心了。您距离伟大之路还有 17 步。现在为你的大脑和肌肉做一些练习。

练习: 第 17 天  

  1. names = ['芬兰'、'瑞典'、'挪威'、'丹麦'、'冰岛'、'爱沙尼亚'、'俄罗斯']。将前五个国家解包,存入一个变量nordic_countries,爱沙尼亚和俄罗斯分别存入es,ru。

🎉恭喜!🎉

<< 第 16 天 || 第 17 天 >> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

舍不得,放不下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值