【问题标题】:Return Variable Referenced Before Assignment返回赋值前引用的变量
【发布时间】:2017-10-30 02:57:47
【问题描述】:

这是我的代码:

    def HTR(S, T):



        while S == 1:
            Z = 60
            if (S == 2):
                Z = 60 + (60*.5)
            elif (S == 3):
                Z = 60*2
            else:
                Z = 0


        return Z

这是我得到的错误:

        return Z
UnboundLocalError: local variable 'Z' referenced before assignment

【问题讨论】:

  • return z 下面的行也是错误信息的一部分.... UnboundLocalError: local variable 'Z' referenced before assignment
  • 那么你想这样做吗?
  • 你认为while S == 1是什么意思?

标签: python python-3.x local


【解决方案1】:

您必须在输入while loop 之前定义Z;否则,在S != 1 的情况下,不会进入循环并且在尝试返回它时Z 是未定义的:

def HTR(S, T):

    Z = None            #<-- choose the value you wish to return is S != 1

    while S == 1:
        Z = 60                 #<-- Z is set to 60
        if (S == 2):               #<-- S already equals 1 at this point
            Z = 60 + (60*.5)
        elif (S == 3):             #<-- S already equals 1 at this point
            Z = 60*2
        else:
            Z = 0              #<-- then Z is always set to zero  
                               # this is probably not the behavior you are expecting!


    return Z

【讨论】:

  • 这段代码的错误远不止这些。
  • 是的,我在代码中添加了 cmets - 其意图是什么并不清楚
【解决方案2】:
def HTR(S, T):
    Z = -1  # init Z
    while S == 1:
        Z = 60
        if (S == 2):
            Z = 60 + (60*.5)
        elif (S == 3):
            Z = 60*2
        else:
            Z = 0

    return Z

在您的代码中,如果 S 不为 1,则不会设置 z。您需要为 Z 赋予初始值。如果 S 不为 1,则返回 -1。

【讨论】:

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