简体   繁体   English

python意外的“预期缩进的块”错误

[英]Unexpected “expected an indented block” error on python

When I run my python program, unexpected "expected an indented block" errors keep popping up. 当我运行python程序时,意外弹出“预期缩进的块”错误,并不断弹出。 I don't see anything wrong with the code, so please help. 我的代码没有发现任何问题,请提供帮助。

def function
    if mode == 1:
    #code
    elif mode == 2:
    #code
    else:
    #code

while True:
    while True:
        #code here

Each time you type : at the end of the line, Python expects a statement or expression indented in the next block. 每次键入:在该行的末尾,Python都希望在下一个块中缩进一个语句或表达式。

To create an "empty" loop, use pass : 要创建“空”循环,请使用pass

def function():
    if mode == 1:
        pass
        # code will go here
    elif mode == 2:
        pass
        # code will go here
    else:
        pass
        # code will go here

while True:
    while True:
        pass
        # code here

the error occurs at the first "While True" loop 错误发生在第一个“ While True”循环中

The reason it happens, is because after the else: Python is expecting a statement or an expression, and since the first one of those is the while True: , and its not indented to be under the else: block you get that exception. 发生这种情况的原因是,在else: Python之后需要一个语句或表达式,并且由于其中的第一个是while True: :,而它并不缩进else:块下,因此会得到该异常。

First of all, after def function there must be parenthesis followed by parenthesis and a colon. 首先,在def function之后必须有括号,然后是括号和冒号。 I'm not sure, but are you indenting after the if statements. 我不确定,但是您是否在if语句之后缩进。 AIs there legit code where your commenting or is that just a comment? 那里的AI合法代码在您的评论中还是仅仅是评论? If there is no code, it will raise an error due to the fact that there must be an indented block after a control line. 如果没有代码,则由于在控制行后必须有一个缩进的块,这将引发错误。 For example, 例如,

def Function(mode):
    if mode == 0:
        print "mode is 0"
    elif mode == 1:
            print "mode is 1"
    else:
        print "unknown mode"
while True:
     while True:
         Function(5)
         #do What ever here

This will not raise an Exception 这不会引发异常

IMPORTANT: Make sure you break your code otherwise it will go forever. 重要说明:确保您破坏了代码,否则它将永远消失。

I figured out the problem, but thanks anyway. 我发现了问题,但还是要感谢。 Python needs you to put code in the if and else statements or else it will think that you forgot to indent in the rest of the code. Python需要您将代码放在if和else语句中,否则它将认为您忘记了其余代码。 But thanks! 但是谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM