我是python新手,目前正在学习如何正确使用函数。在
我的任务是用python为我的作业制作一个bmi计算器。此bmi计算器必须提供使用公制单位还是英制单位的选项。基于此选项,它将要求您的体重和身高在体面的单位类型。这就是问题统计的地方——不管我输入什么,它仍然使用公制单位,似乎忽略了我的if/elif/else语句。所以这是第一个问题,我不明白我哪里出了问题。在
这个问题解决后,它计算的bmi需要归为一个类别,然后程序应该告诉你你的bmi属于哪一个类别,这部分甚至不适用于bmi指标,它只是说:
"""this is the error i keep getting, the actual code for the program is below"""
traceback (most recent call last):
File "C:/Python33/bmi calculator 2 2 2 2.py", line 54, in <module>
catagory(bmi)
File "C:/Python33/bmi calculator 2 2 2 2.py", line 45, in catagory
if bmi <18.5:
TypeError: unorderable types: tuple() < float()
"""this is a bmi calculator that works in both imperial and metric units
and can tell your bmi category"""
bmi = ()
metric = ("metric")
Metric = ("Metric")
imperial = ("imperial")
Imperial = ("Imperial")
MetricBMI = ()
ImperialBMI = ()
answer = input (" Do you want to work out you BMI using Metric or Imperial units?")
def BMI():
metric = ("metric")
Metric = ("Metric")
imperial = ("imperial")
Imperial = ("Imperial")
if answer.lower() == metric:
print("You have chose to calculate your bmi in metric units")
Weight_kg = float(input("What is your weight in kilograms (kg)"))
Height_m = float(input("What is your height in meters (m)?"))
bmi = Weight_kg/Height_m/Height_m
print("Your BMI is " + str(bmi))
elif answer.lower() == imperial:
print ("You have chosen to calculate your bmi in imperial units")
Weight_lbs = float(input("What is your weight in pounds (lbs)?"))
Height_inches = float(input("What is your height in inches??"))
bmi = Weight_lbs*703/Height_inches/Height_inches
print ("Your BMI is " + str(bmi))
else:
print ("please restart and enter either 'imperial' or 'metric'")
BMI()
def catagory(bmi):
if bmi <18.5:
return ("You are underweight")
elif bmi >=18.5 and bmi <25:
return ("You are normal weight")
elif bmi >= 25 and bmi <30:
return ("you are overweight")
elif bmi >=30:
return ("you are obese")
catagory(bmi)
这是你想做的吗?在
你的BMI函数不能返回为BMI计算的值。要改变这一点,您可以让函数将BMI的值返回到主脚本,如上面的“return BMI”所示。或者你可以在你的BMI函数中声明BMI是一个全局变量
由于您的
BMI
函数正在修改全局变量bmi
,因此它需要声明它:如果没有
global
声明,Python将创建一个本地bmi
变量,当函数完成时,该变量将被忽略。您看到的错误是试图使用全局bmi
变量的未更改初始值的结果。最好完全删除此初始化或完全删除全局变量。在相关问题 更多 >
编程相关推荐