在赋值之前引用的返回变量

2024-06-25 23:30:04 发布

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

这是我的代码:

    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

这是我得到的错误:

^{pr2}$

Tags: 代码returnifdef错误elseelifwhile
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。在

在输入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

相关问题 更多 >