Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回赋值前引用的变量_Python_Python 3.x_Local - Fatal编程技术网

Python 返回赋值前引用的变量

Python 返回赋值前引用的变量,python,python-3.x,local,Python,Python 3.x,Local,这是我的代码: 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 这就是我得到的错误

这是我的代码:

    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

在进入
while循环之前,必须定义
Z
;否则,如果
S!=1
,尝试返回循环时未输入循环且未定义循环:

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
def HTR(S,T):
Z=无#

在代码中,如果S不是1,则不会设置z。您需要给Z一个初始值。如果S不是1,将返回-1。

返回Z下面的行也是错误消息的一部分。。。。UnboundLocalError:Assignment之前引用的局部变量“Z”那么您想这样做吗?当S==1时,您认为
是什么意思?此代码的错误远不止于此。是的,我在代码中添加了注释-不清楚其意图是什么
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