Python White Space

From OpenCircuits
Jump to navigation Jump to search

White space in code is space that is blank or white. It can occur anywhere in a line, or an entire line can be white. Typically white space has little meaning in programming. Python is unusual in that white space at the beginning of the line does have a meaning. It is used in conditionas ( if, then, while, until... ) and things like function declarations. White space should also be used to improve the readability of code. The official coding guidelines for Python do not encourage a lot of white space, but I like a lot more. I will illustrate this here, you can make your own decisions. The downside of using a lot of white space for formatting is that it takes some time to do it, otherwise I do not see other issues.


Required White Space

Minor Additions

Blank Lines

Alignment Between Lines

This is probably the most discouraged use of white space since it takes more effort to mainintain. But I think it help illuminate what is going on in the code. I will show you some examples here, I use it in the course, but how you use it is up to you.

Here is the alignment I prefer to read:

make_new_name( "Joe",       "Thomas"        )
make_new_name( "Zelda",     "Thomas"        )
make_new_name( "Woodchuck", "Minederbinder" )
make_new_name( "Joe",       "Biden"         )
make_new_name( "Donald",    "Trump"         )
make_new_name( "Mike",      "Pence"         )
make_new_name( "Tom",       "Clancy"        )

Take the spaces out and it runs the same way, but I think it is a bit harder to read.

make_new_name("Joe","Thomas")
make_new_name("Zelda","Thomas")
make_new_name("Woodchuck","Minederbinder")
make_new_name("Joe","Biden")
make_new_name("Donald","Trump")
make_new_name("Mike","Pence")
make_new_name("Tom","Clancy")


Tabs vs Spaces

There used to be an argument between uber geeks about weather spaces should be inserted using tab ( the tab key ) or spaces using the space bar. There is amusing little story in the TV show silicon valley. Generally for Python this is not an issue, if you use an IDE like Spyder the tab key actually inserts spaces, so use whatever is easier, either way you get spaces. Howvere if you use so odd editor on your computer it may insert tabs, this can really mess up the required white space. So do not do it.