UnboundLocalError:分配前引用的局部变量“BMI”

2024-10-05 14:31:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法得到组合“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)

Tags: orfalsetrueinputifisunitbmi
2条回答
    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))
   ...

这里,如果is_kg==True,第二条语句即elif is_kg==True将不会执行。您可以尝试更高效的方法,而不是添加这么多if-else块,例如:

c1 = int(is_kg==True)
c2 = int(is_inch==True)
# using the concept of binary representation i.e. 00,01,10,11
value = (2*c1)+c2  # generates value between 0 and 3
# add remaining actions, based on your value

在代码中

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

第二个和第四个elif分支永远不会执行,因为这与if .. elif .. else的定义相矛盾

当且仅当所有先前的ifelif(在同一级别!)的条件计算为false时,才会计算elif分支。就你而言,你有

if a == True:
  ...
elif a == True:
  ...

因此,如果a事实上为真,则if的第一个条件计算为true,因此不再计算任何elif条件

一个简单的解决方案是将is_kg == True的所有案例组合到一个分支中,您可以在其中添加额外的if,并将is_kg == False的所有案例组合到第二个分支中,同样在分支中添加if

if is_kg == True:
  if is_inch == True:
    BMI = ...
  else:
    BMI = ...
else:
  if is_inc == True:
    BMI = ...
  else:
    BMI = ...

相关问题 更多 >