【问题标题】:How to fix "IndentationError: expected an indented block" in Python? [closed]如何在 Python 中修复“IndentationError:期望缩进块”? [关闭]
【发布时间】:2018-09-02 19:10:07
【问题描述】:

我正在尝试使用 Python 对 URL 进行 API 测试,我有以下代码块

       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 标准使用 4 个空格缩进
  • if ...:后面需要有一个声明你可以在pass后面加上一个
  • 因为你还没有告诉 if 通过。
  • 为什么我会得到负分

标签: python if-statement indentation


【解决方案1】:

问题是你没有告诉程序当第一个条件满足时要做什么(if 语句)。如果不确定 if 中该怎么做,可以使用 python build in 'pass'。

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

【讨论】:

  • 谢谢,这成功了,继续下一个例外
  • 下一个@Jin 是什么?
  • 我认为这个答案会更有价值,如果你能写一两句话为什么这能解决问题。
  • @syntonym 谢谢
  • @syntonym,这解决了问题,因为我没有为 if 语句设置条件,因此“else”语句存在缩进问题。设置通过条件后,“else”语句不再有缩进问题
【解决方案2】:

这是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

【讨论】:

    【解决方案3】:
    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/")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多