2017-08-11 92 views
0

我是Python新手和一般編程。我想知道如何擺脫這個編譯錯誤局部變量'?'在分配之前引用

def health_risk(activity_level, is_smoker): 
    """Counts the aliveness of a person""" 
    alive = "alive?" or "sedentary" 
    very_low = "low" or "very low" 
    active = "active" or "very active"  
    if (activity_level in alive) and is_smoker is True: 
     xer = "extreme" 
    elif (activity_level in active) and is_smoker is True: 
     xer = "medium"  
    elif (activity_level == alive) and (is_smoker is False): 
     xer = "high"  
    elif (activity_level == very_low) and (is_smoker is False): 
     xer = "medium" 
    elif activity_level == active and is_smoker is False: 
     xer = "low"   
    return xer 
level = health_risk('low', True) 
print(level) 

感謝您的幫助,這是我的第一篇文章,謝謝。

+4

你的'if'語句並沒有覆蓋所有的可能性,所以它可能永遠不會分配給'xer'。此外,你會發現你的類屬性沒有你認爲他們做的值('alive'只是''活着嗎?''因爲''活着嗎?''是一個非空字符串,因此是真的,所以不考慮'或'的第二部分)。 – kindall

+0

你的函數調用不滿足任何'if'語句,因此'return xer'將不起作用 – Mangohero1

+0

另外,你認爲你對這行做了什麼:'alive =「alive?」或「久坐」 –

回答

1

修改要分配給列表的變量語句。

alive = ["alive", "sedentary"] 
very_low = ["low", "very low"] 
active = ["active", "very active"] 

替換所有==in

包括缺少elif聲明。

elif (activity_level in very_low) and (is_smoker is True): 
    xer = "high" # or medium or whatever 

注:以減少冗餘,你可以只是把and is_smoker如果是Trueand not is_smoker如果是False

相關問題