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