为什么我会收到“IndentationError:期望缩进的块”

时间:2017-04-09 21:18:03

标签: python-3.x spyder

我是Python新手所以请怜悯我。 我的环境是:

  macOS Sierra 10.12.4 and Anaconda 4.3.16

我必须遵循以下代码:

import os,
import urllib.request

IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"

if not os.path.exists(IRIS_TRAINING):
    raw = urllib.request.urlopen(IRIS_TRAINING_URL).read()

我在Anaconda Spyder中运行,当我用F9单步执行代码时,我得到:

>>> import os
>>> import urllib.request
>>> IRIS_TRAINING = "iris_training.csv"
>>> IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"
>>> if not os.path.exists(IRIS_TRAINING):
... raw = urllib.request.urlopen(IRIS_TRAINING_URL).read()
  File "<stdin>", line 2
    raw = urllib.request.urlopen(IRIS_TRAINING_URL).read()
      ^
IndentationError: expected an indented block

为什么我收到此错误?

查尔斯

2 个答案:

答案 0 :(得分:0)

(Spyder developer here) The Run a line feature in Spyder (what you get when you press F9) is meant to run full commands, i.e. lines that immediately produce a result. In your case, the line

if not os.path.exists(IRIS_TRAINING):

is not something that produces a result, and hence it generates an error in the next line.

So instead of using F9, I recommend you to use cells instead.

Note: Cells are chunks of code you can create by writing in your code comments of the form #%%. They are run with Shift+Enter from the Editor.

答案 1 :(得分:0)

我有

    '''
    ^
IndentationError: expected an indented block

并且无法找出导致它的原因。看来我不小心在代码的开头缩进了 :)

我删除了这个缩进,一切都变好了!

enter image description here