Python “expected an indented block”

2020-02-04 07:00发布

Let me start off by saying that I am COMPLETELY new to programming. I have just recently picked up Python and it has consistently kicked me in the head with one recurring error -- "expected an indented block" Now, I know there are several other threads addressing this problem and I have looked over a good number of them, however, even checking my indentation has not given me better results. I have replaced all of my indents with 4 spaces and even rewritten the code several times. I'll post this counter assignment I got as an example.

option == 1
while option != 0:
    print "MENU"
    option = input()
    print "please make a selection"
    print "1. count"
    print "0. quit"
    if option == 1:
        while option != 0:
            print "1. count up"
            print "2. count down"
            print "0. go back"
            if option == 1:
                print "please enter a number"
                for x in range(1, x, 1):
                    print x
                elif option == 2:
                    print "please enter a number"
                    for x in range(x, 1, 1):
                elif option == 0:
                    break
                else:
                    print "invalid command"
    elif option == 0:
        break

标签: python
8条回答
女痞
2楼-- · 2020-02-04 07:34

There are several issues:

  1. elif option == 2: and the subsequent elif-else should be aligned with the second if option == 1, not with the for.

  2. The for x in range(x, 1, 1): is missing a body.

  3. Since "option 1 (count)" requires a second input, you need to call input() for the second time. However, for sanity's sake I urge you to store the result in a second variable rather than repurposing option.

  4. The comparison in the first line of your code is probably meant to be an assignment.

You'll discover more issues once you're able to run your code (you'll need a couple more input() calls, one of the range() calls will need attention etc).

Lastly, please don't use the same variable as the loop variable and as part of the initial/terminal condition, as in:

            for x in range(1, x, 1):
                print x

It may work, but it is very confusing to read. Give the loop variable a different name:

            for i in range(1, x, 1):
                print i
查看更多
Luminary・发光体
3楼-- · 2020-02-04 07:35

This one is wrong at least:

            for x in range(x, 1, 1):
        elif option == 0:
查看更多
登录 后发表回答