0

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

Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40
Pro
  • 673
  • 2
  • 6
  • 15

1 Answers1

2

It looks like you're copying and pasting the code into your command prompt, which is why its 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 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
dwb
  • 2,136
  • 13
  • 27