我无法得到组合“K”和“K”的BMI值我和我C’。但是组合“K”和“K”C'和L'和我很好用。我尝试修补“BMI”赋值和elif语句的位置,但函数打印一个空白的BMI值
这是密码
while True:
weight_unit = input('>kg(K) or lbs(L)? ')
if weight_unit.upper() == 'K':
weight = int(input('>Enter weight in kg '))
is_kg = True
break
elif weight_unit.upper() == 'L':
weight = int(input('>Enter weight in lbs '))
is_kg = False
break
else:
print('Please enter K or L. ')
while True:
height_unit = input('>inch(I) or cm(C) ')
if height_unit.upper() == 'I':
height = int(input('>Enter height in inch '))
is_inch = True
break
elif height_unit.upper() == 'C':
height = int(input('>Enter height in cm '))
is_inch = False
break
else:
print('Please enter I or C.')
def BMI_function(weightt,heightt):
global BMI
if is_kg == True:
if is_inch == False:
BMI = (weightt/((heightt*0.01)**2))
elif is_kg == True:
if is_inch == True:
heightt = heightt*2.54
BMI = (weightt/((heightt*0.01)**2))
elif is_kg == False:
if is_inch == True:
BMI = 703*(weightt/(heightt**2))
elif is_kg == False:
if is_inch == False:
height == height*0.393701
BMI = 703*(weightt/(heightt**2))
return BMI
BMI_function(weight,height)
这里,如果
is_kg==True
,第二条语句即elif is_kg==True
将不会执行。您可以尝试更高效的方法,而不是添加这么多if-else块,例如:在代码中
第二个和第四个
elif
分支永远不会执行,因为这与if .. elif .. else
的定义相矛盾当且仅当所有先前的
if
或elif
(在同一级别!)的条件计算为false时,才会计算elif
分支。就你而言,你有因此,如果
a
事实上为真,则if
的第一个条件计算为true
,因此不再计算任何elif
条件一个简单的解决方案是将
is_kg == True
的所有案例组合到一个分支中,您可以在其中添加额外的if
,并将is_kg == False
的所有案例组合到第二个分支中,同样在分支中添加if
相关问题 更多 >
编程相关推荐