【问题标题】:Strange behavior of Python (IndentationError: unexpected indent) - Why?Python 的奇怪行为(IndentationError:意外缩进) - 为什么?
【发布时间】:2021-04-06 01:53:36
【问题描述】:

我有一个奇怪的错误。为什么会这样?

我编写代码,但 Python 向我显示错误,但我没有看到该错误。我已附上屏幕截图。

代码

def func(q):

    def funct(y):
        try:
            print(y)
            exit()

        except:
            pass

    funct(q)

a=['1','2','3','4','5','6','7']
for x in a:
    func(x)

Python

>>> def func(q):
...
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block
>>>     def funct(y):
  File "<stdin>", line 1
    def funct(y):
    ^
IndentationError: unexpected indent
>>>         try:
  File "<stdin>", line 1
    try:
    ^
IndentationError: unexpected indent
>>>             print(y)
  File "<stdin>", line 1
    print(y)
    ^
IndentationError: unexpected indent
>>>             exit()
  File "<stdin>", line 1
    exit()
    ^
IndentationError: unexpected indent
>>>
>>>         except:
  File "<stdin>", line 1
    except:
    ^
IndentationError: unexpected indent
>>>             pass
  File "<stdin>", line 1
    pass
    ^
IndentationError: unexpected indent
>>>
>>>     funct(q)
  File "<stdin>", line 1
    funct(q)
    ^
IndentationError: unexpected indent
>>>
>>> a=['1','2','3','4','5','6','7']
>>> for x in a:
...     func(x)
...
>>>

记事本++:

【问题讨论】:

  • 也许您可以发送文件本身?屏幕截图对我来说很好。
  • REPL 无法知道一个块是否在 1,2,3,...,n 个空行之后继续。因此,一个空行标志着 REPL 上一个块的结束。
  • @CPPCPPCPPCPPCPPCPPCPPCPCPCPPII 使用复制/粘贴,我在 Notepad++ 中写入复制到剪贴板,在 Python 窗口中粘贴。我使用 Windows Notepad++ 和 Linux Python。如果您没有足够的信息,我可以制作一个文件。
  • @kirill 我想你已经得到了正确的答案。没有注意到 是你的文件。
  • @MisterMiyagi 你是什么意思?

标签: python-3.x


【解决方案1】:

看起来您正在将代码复制并粘贴到命令提示符中,这就是它向您抛出错误的原因。在“交互式 python”命令行中输入代码时,如果您留下空白行,Python 会在您完成编写代码时解释并执行它。

最好将代码保存在.py 文件中,然后在命令提示符中使用命令

python folder/to/your/file.py

它将运行您的代码,并允许空行。有关详细信息,请参阅this 问题。


您也可以像这样在命令提示符中使用cd 命令c更改d目录

cd folder/to/your

这会将您的命令提示符“移动”到包含您的 python 文件的文件夹中。这样如果你想运行你的代码,你只需要使用:

python file.py

【讨论】:

    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2022-08-20
    • 2011-04-24
    相关资源
    最近更新 更多