Syntax & Styling

  • No mandatory statement termination characters.
  • Indentation(4 spaces, no tabs).
  • Indent to begin a block, dedent to end one.
  • Statements that expect an indentation level end in a colon(:).
  • CamelCase for classes and lower_case_with_underscores for functions and methods.

  • Refer to PEP 8 for more styling guidelines.

Python Enhancement Proposals(PEP)

PEPs are Python Enhancement Proposals. They describe changes to Python itself, or the standards around it.

Indentation

  • One unusual Python feature is that the whitespace indentation of a piece of code affects its meaning.
  • A logical block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or “if” or whatever. If one of the lines in a group has a different indentation, it is flagged as a syntax error.
  • Indentation(4 spaces, no tabs).
  • Indent to begin a block, dedent to end one.

    lists1

Boiler plate syntax

if __name__ == '__main__':
  main()

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For the main program(program you run), it sets the special __name__ variable to have a value __main__. If this file is being imported from another module, __name__ will be set to the module’s name.

The above mentioned boiler plate syntax avoids the imported module from being executed(Because the imported module’s __name__ is not __main__). It’s not mandatory to have the boiler plate syntax but it is a good practice incase you ever want to import the program you write as a module into other program.

TL:DR: Think about the boiler plate syntax as a piece of code that should just be there at the bottom of your python scripts.

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
>>> 
>>> __name__        # For the program you run, special variable __name__ is assigned value __main__
'__main__'
>>> 
>>> 
>>> import sys      # When you import a module/program, the __name__ variable is set to the module name not __main__
>>> sys.__name__
'sys'

Further reading on this topic: http://stackoverflow.com/questions/419163/what-does-if-name-main-do