赞
踩
本篇我们学习异常处理中的另一种语法形式:try…except…else 语句。
try 语句还支持一个可选的 else 分支,语法如下:
try:
# 业务代码
except:
# 异常处理
else:
# 没有异常时执行的代码
try…except…else 语句的执行过程如下:
接下来我们看几个 try…except…else 语句的示例。
以下示例演示了如何使用 try…except…else clause 开发一个计算体重指数(BMI)的程序:
首先,创建一个基于身高和体重计算 BMI的函数:
def calculate_bmi(height, weight):
""" calculate body mass index (BMI) """
return weight / height**2
然后,定义一个评价 BMI 的函数:
def evaluate_bmi(bmi):
""" evaluate the bmi """
if 18.5 <= bmi <= 24.9:
return 'healthy'
if bmi >= 25:
return 'overweight'
return 'underweight'
最后,定义一个 main() 函数,提示用户输入身高和体重,打印最终的 BMI:
def main():
try:
height = float(input('Enter your height (meters):'))
weight = float(input('Enter your weight (kilograms):'))
except ValueError as error:
print('Error! please enter a valid number.')
else:
bmi = round(calculate_bmi(height, weight), 1)
evaluation = evaluate_bmi(bmi)
print(f'Your body mass index is {bmi}')
print(f'This is considered {evaluation}!')
main() 函数使用 try…except…else 语句控制流程,如果输入的身高或体重不是数字,将会产生 ValueError 异常。如果没有产生异常,将会执行 else 分支,计算 BMI 指数并评级该结果。
以下是完整的代码:
def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2 def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight' def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print(error) else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!') main()
以下示例使用了完整的 try…except…else…finally 语句:
fruits = { 'apple': 10, 'orange': 20, 'banana': 30 } key = None while True: try: key = input('Enter a key to lookup:') fruit = fruits[key.lower()] except KeyError: print(f'Error! {key} does not exist.') except KeyboardInterrupt: break else: print(fruit) finally: print('Press Ctrl-C to exit.')
代码执行过程如下:
如果用户输入的 key 不存在,抛出 KeyError 异常,执行 except 分支。如果用户输入 Ctrl-C,抛出 KeyboardInterrupt 异常,执行 break 语句终止循环。如果在字典 fruits 中找到了输入的 key,打印相应的元素。最后,finally 语句总是会被执行,提示用户输入 Ctrl-C 退出程序。
以上语法形式中,else 分支在 try 分支之后,finally 分支之前执行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。