Blank line is not allowed in python functions?

Viewed 2128

(A) This works:

def func():
    x = 1
    print(x)    
    return

(B) This doesn't work:

def func():
    x = 1

    print(x)    
    return

(C) This also doesn't work: (Here I am using '_' to indicate a white space)

def func():
    x = 1
____
    print(x)    
    return

(D) This works:

def func():
    x = 1
____# some comment
    print(x)    
    return

In both (B) and (C) I get the following errors:

  • NameError: name 'x' is not defined
  • SyntaxError: 'return' outside function

I am using Eclipse and the PyDev plug-in. The Python version is 3.5 and the PyDev version is 4.5.

----------update----------

  1. The issue is not reproducible in Jupyter Notebook and PyCharm.

  2. In Eclipse I have turned on "Show whitespace characters". The indent in (C) is indeed composed of 4 whitespaces which are displayed as 4 dots in the editor. If it was a tab, in the Eclipse editor it would be displayed as ">> ".

Given my through investigation and the comments/answers below, I am pretty sure this is a stupid bug of Eclipse and/or PyDev.

Thank you all for helping.

2 Answers

be careful with tabs and spaces, they are not the same, so:

(_ are withe spaces)

def func():
____x = 1
____
____print(x)
____return

It will work just fine

is not the same as

(+ are tabs, _ white spaces)

def func():
++x = 1
__
++print(x)
++return

Won't work

Answering to your principal question: Blank line is not allowed in python functions?

Blank line is definitely allowed in python functions.

All of yours examples (A,B,C,D) should work and the problem probably (sure) is related to "Eclipse and the PyDev plug-in".

Consider migrating to another IDE like:

And consider using Jupyter Notebook to help your development.

Related