zoukankan      html  css  js  c++  java
  • 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.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.")

    输出的结果如下所示;

     欢迎有问题咨询!

  • 相关阅读:
    JavaStript基础 —— JavaStript语法
    JS拖动滑块验证
    解释型语言和编译型语言、弱类型语言和强类型语言、动态语言和静态语言的区别
    user-select 用户禁止选中
    短地址
    JS实现 Tab栏切换案例
    setAttribute()方法和 getAttribute() 方法
    JS 全局作用域和局部作用域
    数组遍历 forEach 方法
    十进制小数转换为二进制
  • 原文地址:https://www.cnblogs.com/geeksongs/p/12602997.html
Copyright © 2011-2022 走看看