600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python出现错误后怎样返回_Python抛出异常之后返回try语句 直到没有异常出现

python出现错误后怎样返回_Python抛出异常之后返回try语句 直到没有异常出现

时间:2023-06-09 16:57:52

相关推荐

python出现错误后怎样返回_Python抛出异常之后返回try语句 直到没有异常出现

本题目节选自国外某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.393791inches_to_feet= 12

defcalculation():

height_cm= float(input('Enter your height in cm:'))if height_cm <0:raiseValueError()

feet= height_cm * cm_to_inches //inches_to_feet

inch= height_cm * cm_to_inches %inches_to_feetprint("You are {:.0f} feet {:.0f} inches tall!".format(feet, inch))try:

calculation()exceptValueError:print("Only positive numeric inputs are accepted. Please try again.")

calculation()

后来我想了一会儿,废除函数,直接利用while循环就可以让程序只要抛出异常就再次执行try代码块的语句,如果输入数字判断成功,没有异常,则终止循环,使用break语句即可。程序如下;

cm_to_inches = 0.393791inches_to_feet= 12

whileTrue:try:

height_cm= float(input('Enter your height in cm:'))if height_cm <0:raiseValueError()

feet= height_cm * cm_to_inches //inches_to_feet

inch= height_cm * cm_to_inches %inches_to_feetprint("You are {:.0f} feet {:.0f} inches tall!".format(feet, inch))break

exceptValueError:print("Only positive numeric inputs are accepted. Please try again.")

输出的结果如下所示;

欢迎有问题咨询!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。