python代码中的缩进错误

时间:2015-05-29 07:21:13

标签: python indentation

def get_top_grossing_movie_list(url):
movies_list = []
r = requests.get(url)
for each_url in BeautifulSoup(r.text).select('.title a[href*="title"]'):
    movie_title = each_url.text 
    if movie_title != 'X':
        movies_list.append((movie_title, each_url['href']))
return movies_list

在第4行,我得到了:

  

缩进错误:unindent与任何外部缩进级别都不匹配

但我觉得我的缩进是正确的。请给出解决方法。

3 个答案:

答案 0 :(得分:1)

def get_top_grossing_movie_list(url):之后的第二行必须缩进,所有其余代码都相应:

def get_top_grossing_movie_list(url):
    movies_list = []
    r = requests.get(url)
    for each_url in BeautifulSoup(r.text).select('.title a[href*="title"]'):
        movie_title = each_url.text 
        if movie_title != 'X':
            movies_list.append((movie_title, each_url['href']))
    return movies_list 

答案 1 :(得分:0)

请使用空格键4次而不是标签缩进。您可能会收到此错误的原因是因为tab可能不等于4个空格。

答案 2 :(得分:0)

发生def时,如下所示:

  1. 混合标签和空格

  2. 需要添加缩进后,在第一行调用classdef get_top_grossing_movie_list(url): movies_list = [] r = requests.get(url) for each_url in BeautifulSoup(r.text).select('.title a[href*="title"]'): movie_title = each_url.text if movie_title != 'X': movies_list.append((movie_title, each_url['href'])) return movies_list

  3. 您的问题属于第一个语句,因此您的代码必须如下所示:

    {{1}}