为什么当我尝试运行Python脚本时,会得到“预期的缩进块”?

时间:2022-06-21 07:13:38

I have an error which says "expected an indented block" Could you please guide me on how to deal with this error. Thank you:)

我有一个错误,上面写着“期待一个缩进块”,请您指导我如何处理这个错误。谢谢你:)

Code example:

代码示例:

for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) 

6 个解决方案

#1


13  

You are probably mixing tabs with spaces. It looks indented but it really isn't.

您可能将制表符与空格混合。它看起来是缩进的,但实际上不是。


Your code gives me a different error:

你的代码给了我一个不同的错误:

for ch in f:                                                  \
  ( translatedToken = english_hindi_dict[ch] )                \
    if (ch in english_hindi_dict) else (translatedToken = ch)
                                                        ↑

SyntaxError: invalid syntax

Maybe you meant:

也许你的意思:

for ch in f:
  if ch in english_hindi_dict:
    translatedToken = english_hindi_dict[ch]
  else:
    translatedToken = ch

Maybe you meant instead:

也许你的意思相反:

for ch in f:
  translatedToken = english_hindi_dict[ch] if ch in english_hindi_dict else ch

Both should run just fine, and I expect the second to be faster than the former

两者都应该运行得很好,我预计第二个会比第一个快

They both can be optimized into translated = str(english_hindi_dict.get(ch, ch) for ch in f) but that's not the point of the question.

它们都可以优化为translation = str(english_hindi_dict类型)。得到(ch, ch) f中的ch)但这不是问题的重点。

#2


13  

Editing answer to match the code example.

编辑答案以匹配代码示例。

for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)  

is just not valid Python.

是无效的Python。

First, readability count. Your code is hard to read and so, is hard to debug. What's "ch" and "f" ? What's more, you can do one liner in Python but it's not recommended, so put the for in a separate line. Then indent.

首先,可读性计数。您的代码难于阅读,因此难于调试。什么是ch和f ?更重要的是,您可以在Python中执行一行代码,但不推荐这样做,因此将其放到单独的行中。然后缩进。

for chunk in file: 
    ( translatedToken = english_hindi_dict[chunk] ) if (chunk in english_hindi_dict) else (translatedToken = chunk)

Now we can see what's wrong. You make variable assignments in a conditional statement. This is not allowed in Python. I'm guessing you have a C/C++ background and are used to do that. In Python you can't, to prevent you from writing obfuscated code. So you end up with:

现在我们可以看出哪里不对劲了。在条件语句中进行变量赋值。这在Python中是不允许的。我猜你有一个C/ c++背景,并且已经习惯了。在Python中,您不能这样做,以防止编写混乱的代码。结果是

for chunk in file: 
    translatedToken = english_hindi_dict[chunk] if chunk in english_hindi_dict else chunk

This piece of code should work, provided you use Python 2.5+. But the ternary operator is not available in older Python version yet. Let's make it a bit friendlier:

如果您使用Python 2.5+,那么这段代码应该可以工作。但是,ternary操作符在较老的Python版本中是不可用的。让我们让它更友好一些:

for chunk in file: 
    translatedToken = chunk
    if chunk in english_hindi_dict:
        translatedToken = english_hindi_dict[chunk]

You may argue that it's longer to write, and you'd be right. But you spend more time reading code than writing it, so it make sense to make it easy to read. Or course, once you have the Python grip, you will try to make it work in a more pythonic way. Ever heard of EAFTP?

你可能会争辩说,写作时间更长,你是对的。但是你花在阅读代码上的时间要比写代码的时间长,所以让阅读变得容易是有意义的。当然,一旦您掌握了Python控制,您将尝试以更Python化的方式工作。听说过EAFTP吗?

for chunk in file: 
    try:
        translatedToken = english_hindi_dict[chunk]
    except KeyError:
        translatedToken = chunk

But Python is full of surprises, and you'll learn that most of these classic use cases have been already taken care of. The standard library often provides an elegant and short yet readable solution:

但是Python中充满了惊喜,您将了解到这些经典用例中的大多数已经得到了关注。标准库通常提供了一种简洁但可读的解决方案:

for chunk in file: 
    translatedToken = english_hindi_dict.get(chunk, chunk)

As a conclusion: don't try to write Python as you wrote C, or Java as you would write Perl. Other tool, other style.

总结一下:不要像编写C语言那样编写Python,也不要像编写Perl那样编写Java。其他工具,其他风格。


To fix this problem, fire your editor "search and replace" feature and make a huge "replace all" to change all the tabs by 4 spaces, or the contrary. Then indent all your blocks, and finally align all the instructions in the same block.

要解决这个问题,请启动编辑器“搜索和替换”特性,并使用一个巨大的“替换所有”来将所有的选项卡更改为4个空格,或者相反。然后对所有块进行缩进,最后对同一块中的所有指令进行对齐。

Funny that didn't appear before on SO. After all, it's true it's not that obvious.

有趣的是之前没有出现过。毕竟,事实并非如此显而易见。

In Python, you separate blocks using spaces or tabs, not "{".

在Python中,使用空格或制表符分隔块,而不是“{”。

So any time you go down a block (a function, a loop, a class, etc), you have to indent your code. This is not just good practice, this is mandatory. Your program will crash if you don't.

因此,每当您访问一个块(函数、循环、类等)时,都必须缩进代码。这不仅是良好的实践,也是强制性的。如果你不这样做,你的程序就会崩溃。

Now, most of the time, you get this error because you did indent, but used tabs and spaces. In a Python program, you should use either tabs or spaces, but never both in the same files.

现在,大多数情况下,你会得到这个错误,因为你做了缩进,但是使用了制表符和空格。在Python程序中,您应该使用选项卡或空格,但不能同时使用相同的文件。

E.G:

例句:

if (age > 18)
{
    printf("You can vote")
}

Becomes:

就变成:

if age > 18:
    print("You can vote")

In most languages, you could do:

在大多数语言中,你可以做到:

if (age > 18)
{
printf("You can vote")
}

In Python you can't:

在Python中你不能:

if age > 18:
print("You can vote")

raises an exception. What's more, you must align all the instruction of the same block, so:

提出了一个例外。此外,你必须对齐同一块的所有指令,因此:

if age > 18:
    print("You can vote")
    print("How cool is that ?")

Is fine, but:

是可以的,但:

if age > 18:
    print("You can vote")
   print("How cool is that ?")

raises an exception.

提出了一个例外。

Eventually, you can't mix tab and spaces in the same block. So:

最终,您无法在同一块中混合制表符和空格。所以:

if age > 18:
    print("You can vote")
    print("How cool is that ?")

looks good, but will raises an exception. To avoid this problem, just stick to tabs or spaces. The PEP8, the text one most use as a reference for coding style recommend using 4 spaces.

看起来不错,但会有例外。为了避免这个问题,只需使用制表符或空格即可。作为编码风格的参考,最常用的文本PEP8推荐使用4个空格。

Most editors have a global "search and replace" feature that let you fix any problem you can have with that. Some like Geany or Ulipad even have a "replace all tabs with spaces" feature.

大多数编辑器都有一个全局的“搜索和替换”特性,您可以用它来解决任何问题。一些像Geany或Ulipad甚至有“用空格替换所有制表符”的功能。

#3


11  

Python is a language that relies heavily on indentation to decide program structure unlike C and some other languages that use braces for this purpose.

Python是一种非常依赖缩进来决定程序结构的语言,这与C和其他一些使用大括号进行此目的的语言不同。

When you have a statement like:

当你有这样的陈述:

if true:
pass

it will complain because there's no indented statement for the if. You would need to fix it to be:

它会抱怨,因为if没有缩进语句。您需要将其修改为:

if true:
    pass

That sounds like the sort of error you have, though it may have been more obvious had you posted the actual code. When stating a problem, it's a good idea to give the code and explain what the expected behaviour was and how that related to the actual behaviour. You'll make the lives of those trying to help you out that much easier :-)

这听起来像是您遇到的那种错误,尽管如果您发布了实际的代码,可能会更明显。在说明问题时,最好给出代码并解释预期行为是什么,以及它与实际行为之间的关系。你将使那些试图帮助你的人的生活更容易:

Also keep in mind that you may get this problem even if your code looks right. Mixing spaces and tabs in your source code can often lead to this.

还要记住,即使您的代码看起来是正确的,您也可能会遇到这个问题。在源代码中混合空格和制表符常常会导致这种情况。

#4


3  

IndentationErrors can be caused by a lot if different things. Off the top of my head:

如果事情不同,许多错误都可能导致。在我的头顶上:

  • Forgetting to indent at all.

    忘记缩进。

    Python uses indents to delimit syntactic blocks. For example:

    Python使用缩进来分隔语法块。例如:

    if will_is_awesome:
        print "You're right"
    else:
        print "You lie!"
    

    You will get an IndentationError: expected an indented block error if you forget to indent. For example:

    您将得到一个IndentationError:如果忘记缩进,则预期会出现缩进块错误。例如:

    if will_is_awesome:
    print "You're right"
    else:
    print "You lie!"
    
  • Commenting out an indented block.

    注释缩进的块。

    For example:

    例如:

    if light_is_green:
        go_now()
    else:
        # go_anyway()
    do_something_else()
    

    This will produce an IndentationError: expected an indented block because the comment makes the line after else: look empty to the parser. Adding a pass statement will fix the problem. Eg:

    这将产生一个IndentationError:预期一个缩进的块,因为该注释会使该行后面的行:对解析器看空。添加pass语句将修复问题。例如:

    if light_is_green:
        go_now()
    else:
        # go_anyway()
        pass
    do_something_else()
    
  • Mixed tabs and spaces in indents.

    在缩进中混合制表符和空格。

    Tab stops can vary between different machines and editors. If you mix tabs and spaces just right, you can get your error, but it usually produces IndentationError: unindent does not match any outer indentation level, so it's unlikely to be your problem. It's worth knowing anyway. It is advisable to never use tabs in Python code.

    制表符停止在不同的机器和编辑器之间是不同的。如果正确地混合制表符和空格,就可以得到错误,但它通常会产生IndentationError: unindent与任何外部缩进级别都不匹配,所以这不太可能是您的问题。值得了解的。最好不要在Python代码中使用制表符。

#5


2  

Python uses indentation (spaces/tabs in front of your code lines) to indicate where a block of code starts and ends, relative to what python statement precedes it.

Python使用缩进(代码行前面的空格/制表符)来指示代码块开始和结束的位置,相对于前面的Python语句。

So, taking PHP for example:

以PHP为例:

if ($blah == 'foo')
{
  // this is line 1 of my code block
  // this is line 2
}

Would, under python, be:

在python,是:

if blah == 'foo':
    # this is line 1 of my code block
    # this is line 2
    pass

Could you please provide some code, together with the exact error?

能否提供一些代码,以及准确的错误?

#6


1  

Python determines blocks by indentation, not by characters { and } like C/C++/Java/PHP/... does or by if/endif or begin/end pairs found in some other languages. So you have to be careful about indentation - also mixing tabs and spaces is not good.

Python通过缩进来确定块,而不是像C/C++/Java/PHP/…是否或通过if/endif或开始/结束对在其他语言中找到。所以你必须小心缩进——混合制表符和空格也不好。

#1


13  

You are probably mixing tabs with spaces. It looks indented but it really isn't.

您可能将制表符与空格混合。它看起来是缩进的,但实际上不是。


Your code gives me a different error:

你的代码给了我一个不同的错误:

for ch in f:                                                  \
  ( translatedToken = english_hindi_dict[ch] )                \
    if (ch in english_hindi_dict) else (translatedToken = ch)
                                                        ↑

SyntaxError: invalid syntax

Maybe you meant:

也许你的意思:

for ch in f:
  if ch in english_hindi_dict:
    translatedToken = english_hindi_dict[ch]
  else:
    translatedToken = ch

Maybe you meant instead:

也许你的意思相反:

for ch in f:
  translatedToken = english_hindi_dict[ch] if ch in english_hindi_dict else ch

Both should run just fine, and I expect the second to be faster than the former

两者都应该运行得很好,我预计第二个会比第一个快

They both can be optimized into translated = str(english_hindi_dict.get(ch, ch) for ch in f) but that's not the point of the question.

它们都可以优化为translation = str(english_hindi_dict类型)。得到(ch, ch) f中的ch)但这不是问题的重点。

#2


13  

Editing answer to match the code example.

编辑答案以匹配代码示例。

for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)  

is just not valid Python.

是无效的Python。

First, readability count. Your code is hard to read and so, is hard to debug. What's "ch" and "f" ? What's more, you can do one liner in Python but it's not recommended, so put the for in a separate line. Then indent.

首先,可读性计数。您的代码难于阅读,因此难于调试。什么是ch和f ?更重要的是,您可以在Python中执行一行代码,但不推荐这样做,因此将其放到单独的行中。然后缩进。

for chunk in file: 
    ( translatedToken = english_hindi_dict[chunk] ) if (chunk in english_hindi_dict) else (translatedToken = chunk)

Now we can see what's wrong. You make variable assignments in a conditional statement. This is not allowed in Python. I'm guessing you have a C/C++ background and are used to do that. In Python you can't, to prevent you from writing obfuscated code. So you end up with:

现在我们可以看出哪里不对劲了。在条件语句中进行变量赋值。这在Python中是不允许的。我猜你有一个C/ c++背景,并且已经习惯了。在Python中,您不能这样做,以防止编写混乱的代码。结果是

for chunk in file: 
    translatedToken = english_hindi_dict[chunk] if chunk in english_hindi_dict else chunk

This piece of code should work, provided you use Python 2.5+. But the ternary operator is not available in older Python version yet. Let's make it a bit friendlier:

如果您使用Python 2.5+,那么这段代码应该可以工作。但是,ternary操作符在较老的Python版本中是不可用的。让我们让它更友好一些:

for chunk in file: 
    translatedToken = chunk
    if chunk in english_hindi_dict:
        translatedToken = english_hindi_dict[chunk]

You may argue that it's longer to write, and you'd be right. But you spend more time reading code than writing it, so it make sense to make it easy to read. Or course, once you have the Python grip, you will try to make it work in a more pythonic way. Ever heard of EAFTP?

你可能会争辩说,写作时间更长,你是对的。但是你花在阅读代码上的时间要比写代码的时间长,所以让阅读变得容易是有意义的。当然,一旦您掌握了Python控制,您将尝试以更Python化的方式工作。听说过EAFTP吗?

for chunk in file: 
    try:
        translatedToken = english_hindi_dict[chunk]
    except KeyError:
        translatedToken = chunk

But Python is full of surprises, and you'll learn that most of these classic use cases have been already taken care of. The standard library often provides an elegant and short yet readable solution:

但是Python中充满了惊喜,您将了解到这些经典用例中的大多数已经得到了关注。标准库通常提供了一种简洁但可读的解决方案:

for chunk in file: 
    translatedToken = english_hindi_dict.get(chunk, chunk)

As a conclusion: don't try to write Python as you wrote C, or Java as you would write Perl. Other tool, other style.

总结一下:不要像编写C语言那样编写Python,也不要像编写Perl那样编写Java。其他工具,其他风格。


To fix this problem, fire your editor "search and replace" feature and make a huge "replace all" to change all the tabs by 4 spaces, or the contrary. Then indent all your blocks, and finally align all the instructions in the same block.

要解决这个问题,请启动编辑器“搜索和替换”特性,并使用一个巨大的“替换所有”来将所有的选项卡更改为4个空格,或者相反。然后对所有块进行缩进,最后对同一块中的所有指令进行对齐。

Funny that didn't appear before on SO. After all, it's true it's not that obvious.

有趣的是之前没有出现过。毕竟,事实并非如此显而易见。

In Python, you separate blocks using spaces or tabs, not "{".

在Python中,使用空格或制表符分隔块,而不是“{”。

So any time you go down a block (a function, a loop, a class, etc), you have to indent your code. This is not just good practice, this is mandatory. Your program will crash if you don't.

因此,每当您访问一个块(函数、循环、类等)时,都必须缩进代码。这不仅是良好的实践,也是强制性的。如果你不这样做,你的程序就会崩溃。

Now, most of the time, you get this error because you did indent, but used tabs and spaces. In a Python program, you should use either tabs or spaces, but never both in the same files.

现在,大多数情况下,你会得到这个错误,因为你做了缩进,但是使用了制表符和空格。在Python程序中,您应该使用选项卡或空格,但不能同时使用相同的文件。

E.G:

例句:

if (age > 18)
{
    printf("You can vote")
}

Becomes:

就变成:

if age > 18:
    print("You can vote")

In most languages, you could do:

在大多数语言中,你可以做到:

if (age > 18)
{
printf("You can vote")
}

In Python you can't:

在Python中你不能:

if age > 18:
print("You can vote")

raises an exception. What's more, you must align all the instruction of the same block, so:

提出了一个例外。此外,你必须对齐同一块的所有指令,因此:

if age > 18:
    print("You can vote")
    print("How cool is that ?")

Is fine, but:

是可以的,但:

if age > 18:
    print("You can vote")
   print("How cool is that ?")

raises an exception.

提出了一个例外。

Eventually, you can't mix tab and spaces in the same block. So:

最终,您无法在同一块中混合制表符和空格。所以:

if age > 18:
    print("You can vote")
    print("How cool is that ?")

looks good, but will raises an exception. To avoid this problem, just stick to tabs or spaces. The PEP8, the text one most use as a reference for coding style recommend using 4 spaces.

看起来不错,但会有例外。为了避免这个问题,只需使用制表符或空格即可。作为编码风格的参考,最常用的文本PEP8推荐使用4个空格。

Most editors have a global "search and replace" feature that let you fix any problem you can have with that. Some like Geany or Ulipad even have a "replace all tabs with spaces" feature.

大多数编辑器都有一个全局的“搜索和替换”特性,您可以用它来解决任何问题。一些像Geany或Ulipad甚至有“用空格替换所有制表符”的功能。

#3


11  

Python is a language that relies heavily on indentation to decide program structure unlike C and some other languages that use braces for this purpose.

Python是一种非常依赖缩进来决定程序结构的语言,这与C和其他一些使用大括号进行此目的的语言不同。

When you have a statement like:

当你有这样的陈述:

if true:
pass

it will complain because there's no indented statement for the if. You would need to fix it to be:

它会抱怨,因为if没有缩进语句。您需要将其修改为:

if true:
    pass

That sounds like the sort of error you have, though it may have been more obvious had you posted the actual code. When stating a problem, it's a good idea to give the code and explain what the expected behaviour was and how that related to the actual behaviour. You'll make the lives of those trying to help you out that much easier :-)

这听起来像是您遇到的那种错误,尽管如果您发布了实际的代码,可能会更明显。在说明问题时,最好给出代码并解释预期行为是什么,以及它与实际行为之间的关系。你将使那些试图帮助你的人的生活更容易:

Also keep in mind that you may get this problem even if your code looks right. Mixing spaces and tabs in your source code can often lead to this.

还要记住,即使您的代码看起来是正确的,您也可能会遇到这个问题。在源代码中混合空格和制表符常常会导致这种情况。

#4


3  

IndentationErrors can be caused by a lot if different things. Off the top of my head:

如果事情不同,许多错误都可能导致。在我的头顶上:

  • Forgetting to indent at all.

    忘记缩进。

    Python uses indents to delimit syntactic blocks. For example:

    Python使用缩进来分隔语法块。例如:

    if will_is_awesome:
        print "You're right"
    else:
        print "You lie!"
    

    You will get an IndentationError: expected an indented block error if you forget to indent. For example:

    您将得到一个IndentationError:如果忘记缩进,则预期会出现缩进块错误。例如:

    if will_is_awesome:
    print "You're right"
    else:
    print "You lie!"
    
  • Commenting out an indented block.

    注释缩进的块。

    For example:

    例如:

    if light_is_green:
        go_now()
    else:
        # go_anyway()
    do_something_else()
    

    This will produce an IndentationError: expected an indented block because the comment makes the line after else: look empty to the parser. Adding a pass statement will fix the problem. Eg:

    这将产生一个IndentationError:预期一个缩进的块,因为该注释会使该行后面的行:对解析器看空。添加pass语句将修复问题。例如:

    if light_is_green:
        go_now()
    else:
        # go_anyway()
        pass
    do_something_else()
    
  • Mixed tabs and spaces in indents.

    在缩进中混合制表符和空格。

    Tab stops can vary between different machines and editors. If you mix tabs and spaces just right, you can get your error, but it usually produces IndentationError: unindent does not match any outer indentation level, so it's unlikely to be your problem. It's worth knowing anyway. It is advisable to never use tabs in Python code.

    制表符停止在不同的机器和编辑器之间是不同的。如果正确地混合制表符和空格,就可以得到错误,但它通常会产生IndentationError: unindent与任何外部缩进级别都不匹配,所以这不太可能是您的问题。值得了解的。最好不要在Python代码中使用制表符。

#5


2  

Python uses indentation (spaces/tabs in front of your code lines) to indicate where a block of code starts and ends, relative to what python statement precedes it.

Python使用缩进(代码行前面的空格/制表符)来指示代码块开始和结束的位置,相对于前面的Python语句。

So, taking PHP for example:

以PHP为例:

if ($blah == 'foo')
{
  // this is line 1 of my code block
  // this is line 2
}

Would, under python, be:

在python,是:

if blah == 'foo':
    # this is line 1 of my code block
    # this is line 2
    pass

Could you please provide some code, together with the exact error?

能否提供一些代码,以及准确的错误?

#6


1  

Python determines blocks by indentation, not by characters { and } like C/C++/Java/PHP/... does or by if/endif or begin/end pairs found in some other languages. So you have to be careful about indentation - also mixing tabs and spaces is not good.

Python通过缩进来确定块,而不是像C/C++/Java/PHP/…是否或通过if/endif或开始/结束对在其他语言中找到。所以你必须小心缩进——混合制表符和空格也不好。