Pro
Pro

Reputation: 727

IndentationError when copying code into the Python REPL/Interpreter

I have a strange error. Why does it happen?

I write code, but Python shows me the error, but I don't see that error. I've attached the screenshot.

Code

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)
...

Notepad++:

Enter image description here

Upvotes: 0

Views: 829

Answers (1)

dwb
dwb

Reputation: 2644

It looks like you're copying and pasting the code into your command prompt, which is why it’s throwing you an error. When typing code in the "interactive Python" command line, if you leave a blank line Python interprets that as you having finished writing code, and executes it.

You're much better off saving your code in a .py file, and then in the command prompt using the command

python folder/to/your/file.py

which will run your code, and allow blank lines. See this question for more information.


You could also change directory by using the cd command in the command prompt like so:

cd folder/to/your

Which will "move" your command prompt into the folder containing your Python file. That way if you want to run your code, you only need to use:

python file.py

Upvotes: 3

Related Questions