Python抛出异常之后返回try语句,直到没有异常出现
2023-09-11 14:21:08 时间
本题目节选自国外某top50高校Python练习题库,重点在于我们返回try语句的方法,而不是题目给出的背景。假设我们写一个程序,可以将输入的身高厘米数转化为英寸,如果遇到了负数,字母,中文等则抛出异常,并输出“Only positive numeric inputs are accepted. Please try again.”,最后再返回到输入input函数当中,要求用户再次进行输出(重点)。一个人的身高只能是正数。如果遇到了正数,则数值输入正确,开始进行计算,计算完成后输出“You are x feet y inches tall!”,x和y分别代表了计算之后的值。英文原文如下,感兴趣的可以看看:
最开始我尝试了用函数来解决这个问题,表面上看起来是对的,但是很快挂了,因为进行第二次输入异常值的时候,程序会报错,正确的应该是只要有错误值,就不断要求用户进行输入新的正确的值。用函数进行接收异常的except代码块里再次执行一个接收数字再进行计算的calculation()函数,因为这样except代码块里的calculation()函数并不在try语句里,无法用expect进行接收。如下所示:
cm_to_inches = 0.393791 inches_to_feet = 12 def calculation(): height_cm = float(input('Enter your height in cm: ')) if height_cm < 0: raise ValueError() feet = height_cm * cm_to_inches // inches_to_feet inch = height_cm * cm_to_inches % inches_to_feet print("You are {:.0f} feet {:.0f} inches tall!".format(feet, inch)) try: calculation() except ValueError: print("Only positive numeric inputs are accepted. Please try again.") calculation()
后来我想了一会儿,废除函数,直接利用while循环就可以让程序只要抛出异常就再次执行try代码块的语句,如果输入数字判断成功,没有异常,则终止循环,使用break语句即可。程序如下;
cm_to_inches = 0.393791 inches_to_feet = 12 while True: try: height_cm = float(input('Enter your height in cm: ')) if height_cm < 0: raise ValueError() feet = height_cm * cm_to_inches // inches_to_feet inch = height_cm * cm_to_inches % inches_to_feet print("You are {:.0f} feet {:.0f} inches tall!".format(feet, inch)) break except ValueError: print("Only positive numeric inputs are accepted. Please try again.")
输出的结果如下所示;
欢迎有问题咨询!
相关文章
- python -- numpy 基本数据类型,算术运算,组合,分割 函数
- Python 中 异步协程 的 使用方法介绍
- python是否存在某个字符串 效率最高_Python中判断子串存在的性能比较及分析总结...
- 【华为OD机试真题 python】不含 101 的数【2022 Q4 | 100分】
- 【华为OD机试真题 python】工号不够用了怎么办? 【2022 Q4 | 100分】
- 《python源代码剖析》笔记 python中的List对象
- 2023版python安装教程奉上,Python永久使用 超详细版,一看就会【小白友好】
- 152 python网络编程 - TCP服务器
- python flask-caching模块缓存详解
- python实例 异常处理
- 【Python行业分析3】BOSS直聘招聘信息获取之爬虫程序分析
- Python之文件系统操作(pathlib)
- 2.1 The Python Interpreter(python解释器)
- 一个python实现重试机制的简要实践
- 【Python】python 库分类大全
- 学习笔记(33):Python网络编程&并发编程-进程池线程池
- python升级带来的yum异常:File "/usr/bin/yum", line 30
- 不同操作系统Windows/Linux/MacOS中python环境通过pip安装mysqlclient遇到的问题及解决方案
- [Python]python+yaml三行代码完成配置文件灵活读取与warning:YAMLLoadWarning处理
- [Python]2分钟完成python + Selenium Web端自动化环境搭建,开启~~~
- Python opencv-python 简单测试
- Python入门学习笔记第十章——文件和异常~~~
- [Python] 对字典按照key/value进行排序