在Python的if / else语句中,return语句不会返回值

2024-04-18 22:39:03 发布

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

在这个函数中,我想返回一个列表,如果它不是空的。为了检查列表是否为空,我使用if not data:并测试它是否被填充了我使用elif data:的内容,但是当len(data)等于13时,return语句没有执行。原因是什么?在

当列表为空时,使用新的startend参数再次调用该函数,直到data被填充。在

Class MyClass:

    def downloadHistoryOHLC(url, start, end):

        http = urllib.request.urlopen(url)
        data = json.loads(http.read().decode())

        print('length is', len(data))      # Here I test if list is filled  

        if not data:

            ''' Add 366 days to start date if list is empty '''

            start = datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
            start = str(start.isoformat()+'Z')

            end = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
            end = str(end.isoformat()+'Z')

            MyClass.downloadHistoryOHLC(url, start, end) # if list is empty I execute the same function with new parameters

        elif data:

            return data

当我执行这个函数时,我可以看到列表的长度是13,但是没有返回任何数据。在

^{pr2}$

Tags: 函数url列表datalenreturnifis
2条回答

正如Paul在评论部分指出的,我在调用函数时错过了返回。在

Class MyClass:

    def downloadHistoryOHLC(url, start, end):

        http = urllib.request.urlopen(url)
        data = json.loads(http.read().decode())

        print('length is', len(data))      # Here I test if list is filled  

        if not data:

            ''' Add 366 days to start date if list is empty '''

            start = datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
            start = str(start.isoformat()+'Z')

            end = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
            end = str(end.isoformat()+'Z')

            return(MyClass.downloadHistoryOHLC(url, start, end)) # if list is empty I execute the same function with new parameters

        return data

也许用else代替elif会更好:

else:
    return data

相关问题 更多 >