关键词搜索

源码搜索 ×
×

Python抛出异常之后返回try语句,直到没有异常出现

发布2021-01-13浏览626次

详情内容

本题目节选自国外某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语句即可。程序如下python基础教程;

    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.")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出的结果如下所示;

    在这里插入图片描述

    欢迎有问题咨询!

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载