簡體   English   中英

Python 3.2.2函數在非空變量上返回None

[英]Python 3.2.2 Function Returns None on Non-Empty Variable

我正在編寫一個簡單的腳本來下載.mp4 TEDTalks給出一個TEDTalk網站鏈接列表:

# Run through a list of TEDTalk website links and download each
# TEDTalk in high quality MP4

import urllib.request

#List of website links
l = [
        "http://www.ted.com/index.php/talks/view/id/28",
        "http://www.ted.com/index.php/talks/view/id/29",
    ]

# Function which takes the location of the string "-480p.mp4",
# d = 1 less that location, and a string and returns the
# full movie download link
def findFullURL(d, e, s):
    a = s[d]
    if a != "/":
        #Subtract from d to move back another letter
        d = d - 1
        findFullURL(d, e, s)
    else:
        fullURL = "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"
        #print(fullURL)
        return fullURL

#Iterate through a list of links to download each movie
def iterateList(l):
    for x in l:
        #get the HTML
        f = urllib.request.urlopen(x)
        #Convert the HTML file into a string
        s = str(f.read(), "utf-8")
        f.close()
        #Find the location in the string where the interesting bit ends
        e = s.find("-480p.mp4")
        d = e - 1
        #The problem is with this variable url:
        url = findFullURL(d, e, s)
        print("Downloading " + url)
        #TODO: Download the file

我確信函數findFullURL有效。 如果取消注釋findFullURL函數末尾的print(fullURL)行,您將看到它完全按照我的需要輸出下載鏈接。

但是,在我嘗試通過url = findFullURL(d, e, s)捕獲該字符串的iterateList函數中,變量url似乎采用值None 我根本不明白這一點。 它應該像下面的例子一樣簡單,當我在解釋器中嘗試時它可以工作:

def hello():
    return "Hello"
url = hello()
print(url)

我確信函數findFullURL有效。

確保某段代碼可以正常運行,這是浪費數小時調試時間在錯誤位置的最佳方法。

事實上,該功能不起作用。 你錯過了一個回報:

def findFullURL(d, e, s):
    a = s[d]
    if a != "/":
        #Subtract from d to move back another letter
        d = d - 1
        return findFullURL(d, e, s)   # <<<<<<< here
    else:
        fullURL = "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"
        #print(fullURL)
        return fullURL

此外,您不應該使用遞歸來解決此任務。 你可以改用rfind

def findFullURL(d, e, s):
    d = s.rfind('/', 0, d + 1)
    # You probably want to handle the condition where '/' is not found here.
    return "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"

findFullURLif語句的第一個分支上沒有return語句。 在Python中,這意味着它返回None

暫無
暫無

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

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