if else - IndentationError:预期缩进块[关闭]

问题描述 投票:-4回答:3

我有以下代码块

   def simple_get(url):
    try:
        page_response = requests.get(page_link, timeout=5)
        if page_response.status_code == 200:
        # extract
        else:
            print(page_response.status_code)
            # notify, try again
    except requests.Timeout as e:
        print("It is time to timeout")
        print(str(e))
    except # other exception

当我运行它给我以下错误

File "<ipython-input-16-6291efcb97a0>", line 11
else:
   ^
IndentationError: expected an indented block

我不明白为什么当我已经将“else”语句缩进时,笔记本仍然要求缩进

python if-statement indentation
3个回答
1
投票

问题是,当满足第一个条件时(如果声明),您没有告诉程序该做什么。如果您不确定if中的操作,可以在'pass'中使用python build。

if page_response.status_code == 200:
    pass
else:
    print(page_response.status_code)

0
投票

这是Python开始编码的一个非常基本的概念: 以#开头的行在代码块中被忽略。

这里的代码

    if page_response.status_code == 200:
    # extract
    else:
        print(page_response.status_code)

字面翻译为

    if page_response.status_code == 200:
    else:
        print(page_response.status_code)

因此产生IndentationError

你可以通过将至少pass命令或任何工作线放入if语句来解决它。

之前已经提出过类似的问题: Python: Expected an indented block


0
投票
import requests
from bs4 import BeautifulSoup
def simple_get(url):
    try:
        page_response = requests.get(url, timeout=5)
        if page_response.status_code == 200:
            print(page_response.status_code)
            pass
            # extract
        else:
            print(page_response.status_code)
            # notify, try again
    except requests.Timeout as e:

        print("It is time to timeout")
        print(str(e))
simple_get("https://www.nytimes.com/")
© www.soinside.com 2019 - 2024. All rights reserved.