我是python的新手,只是学习如何调试和测试我的代码。 我们必须为课程编写一个小的BMI计算器。但是,如果我尝试通过测试运行它,则会收到错误消息:
Please enter only non-negative numbers.
Failure <Click to see difference>
**********************************************************************
File "C:/Users/TAGI/PycharmProjects/703410_U7_Tests/Programs/BMI/task.py", line 39, in task.bmi
Failed example:
bmi(-1, 200)
Expected:
Please enter only non-negative numbers.
Got:
Please enter only non-negative numbers.
-0.25
为什么在引发异常后仍然使用负数计算结果?如果我注释掉我的doctests并在没有它的情况下尝试,那就很好。这是我的代码(已注释掉doctests):
def check_variables(a):
try:
float(a)
if a < 0:
raise ValueError
except ValueError:
print("Please enter only non-negative numbers.")
except:
print("This is an error: something went wrong. Please try again.")
return a
def bmi(a_weight, a_height):
# TODO: write docstring for this function
"""
This function returns the bmi of a person and tests the values. If they are invalid it returns an error.
:param a_weight: a real number, the users weight
:param a_height: a real number, the users height
:return: bmi of user
:rtype: float
# >>> bmi(10,0)
Traceback (most recent call last):
...
ZeroDivisionError: float division by zero
# >>> round(bmi(75,175), 1)
24.5
# >>> bmi("abc",177)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for /: 'str' and 'float'
# >>> bmi(0, 180)
0.0
# >>> bmi(-1, 200)
Please enter only non-negative numbers.
# >>> bmi(100, -40)
Please enter only non-negative numbers.
# TODO: write doctest for this function
"""
return check_variables(a_weight) / (check_variables(a_height)/100) ** 2
bmi(-10, 180)