python while true try except_Python中的try,except和while循环

正如SpoonMeiser已经提到的,您的代码有很多问题:The only division takes place before entering the try block, so your except ZeroDivisionError will never get triggered.

except user_input_1 != int evaluates to except True which is meaningless and will never get triggered

The only way you don't hit a break in your while loop, is if you throw an exception that gets caught (if it's not caught, it'll

escape your while loop and exit your program). Since the code that

gets user input is outside of the while loop, there would be (if

the exceptions could ever be caught) no difference and you'd see the

error messages just repeating forever.

其他错误包括:使用b in range(x, y):这些值仅包含该间隔中的整数值。你可以用以下方法进行测试:print(2.1 in range(0,10)) # Prints: False

print(2 in range(0,10)) # Prints: True

如果您总是将用户输入用作= float(input(...)),那么您应该从一开始就使用= float(input(...)):,只需执行一次。

b = 'BMI'?

下面是生成的代码:def foo():

try:

user_input_1 = float(input('What is your weight? '))

user_input_2 = float(input('What is your height? '))

if all(x>0 for x in [user_input_1,user_input_2]):

b = user_input_1/user_input_2**2

print(b)

if 0 > b > 26:

print('You are skinny as a rail')

elif 19 > b > 26:

print("You are fit as a butcher's dog")

else:

print('You are as plum as a partridge')

else: raise ValueError

except ValueError:

print('Enter your height in meters as a float')

foo()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值