簡體   English   中英

if / else語句中的return語句不會在Python中返回值

[英]Return statement in a if/else statement doesn't return value in Python

在這個函數中,我想返回一個列表,如果它不是空的。 要檢查列表是否為空我使用if not data:並測試它是否填充了我使用elif 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但沒有返回數據。

In [844]: mylist = MyClass.downloadHistoryOHLC(start, end, coin_id, name)
length is 0
length is 0
length is 0
length is 0
length is 13

In [845]: mylist

In [846]:

也許它會更好地使用else而不是elif:

else:
    return data

正如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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM