python try语句如何使用lcdnumber_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 = 12def calculation():

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

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()

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

calculation()

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

cm_to_inches = 0.393791inches_to_feet = 12while True:try:

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

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))breakexcept ValueError:print("Only positive numeric inputs are accepted. Please try again.")

输出的结果如下所示;

欢迎有问题咨询!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值