【问题标题】:local variable '?' referenced before assignment局部变量“?”赋值前引用
【发布时间】:2017-08-12 09:10:25
【问题描述】:

我是 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)

感谢您的帮助,这是我的第一篇文章,谢谢。

【问题讨论】:

  • 您的if 语句并未涵盖所有可能性,因此可能永远不会分配给xer。此外,您会发现您的类属性没有您认为的值(alive 只是"alive?",因为"alive?" 是一个非空字符串,因此是真实的,所以@987654327 的第二部分@ 不考虑)。
  • 您的函数调用不满足任何if 语句,因此return xer 将不起作用
  • 顺便说一句,你认为你在用这条线做什么:alive = "alive?" or "sedentary"

标签: python


【解决方案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

注意:为了减少冗余,如果是True,你可以只输入and is_smoker,如果是False,你可以输入and not is_smoker

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 2011-11-06
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多