异常处理
Python使用try和except来优雅地处理错误。优雅的退出(或优雅的处理)错误是一个简单的编程习惯 - 一个程序检测到严重的错误条件并“优雅地”退出,以一种受控的方式。通常程序在优雅退出的时候会打印一个描述性的错误信息到终端或日志中,这使得我们的应用程序更为健壮。异常的原因通常是程序本身外部的。异常的例子可以是错误的输入,错误的文件名,不能找到文件,IO设备的故障等。优雅地处理错误可以防止我们的应用程序崩溃。
我们在前面的章节中已经介绍了不同的Python错误类型。如果我们在程序中使用try和except,那么它不会在这些块中引发错误。

try:
如果一切顺利,请在此块中编写代码
except:
如果出了问题,会运行此块中的代码
示例:
try:
print(10 + '5')
except:
print('Something went wrong')
在上面的例子中,第二个操作数是字符串。我们可以将其更改为float或int以将其与数字相加,使其工作。但是,如果没有任何更改,第二个块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:
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) # 常规调用与单独的参数
print(list(numbers)) # [2, 3, 4, 5, 6]
args = [2, 7]
numbers = range(*args) # **带有从列表中展开的参数的调用**
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 函数。我们可以使用打包方法使我们的函数能够使用无限数量或任意数量的参数。
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):
# 检查kwargs的类型是否为字典类型
# print(type(kwargs))
# 打印字典项
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.
zip
有时在循环列表时,我们希望将它们组合在一起。请参见下面的示例:
评论区