Select Page

Python Programming Overview 2

by | 25-Dec-2020 | DevOps, Programming

Python Programming Overview 2

(1) Indentation

Python & Whitespace

  • Whitespace is significant in Python (sorf of)
    • Text editor: vim, notepad++
  • Makes for significantly more readable code
  • Whitespace is only “significant” at the very left of your statements, to denote blocks

 

Code Blocks

  • Indenting denotes the beginning of a block; “outdenting” or “dedenting” denotes the end of the block
  • Blocks include: classes, functions, if statements, loops, other control structures

 

Everything Else

  • In other part of the code, whitespace is actually not significant, and you are free to use it how you like
  • Examples include arbitrary newlines, implicit or explicit continuation lines

 

Exercises

  • Run the Python interpreter
  • Define a function with an arbitrary name and no arguments
  • Press enter, then type print ‘hi!’ and press Enter
  • Repeat the above two steps, but press the tab key before you type the print statement

(2) Spaces Over Tabs

A Warning

  • Stick to one or the other (Don’t mix them!)
    • Even if you are writing C, it’s not safe to mix spaces and tabs in your source code
    • Beware the war of tabs vs. spaces

 

The Case for Spaces

  • PEP 8 identifies spaces as preferred over tabs
    • PEP 8 is a style guideline for Python
  • Besides that, there is no real requirement (only that you do not mix the two)
  • Code or text editors can be configured to insert 4 (or any number of) spaces in place of a tab

 

Editor Suggestions

  • A few suggestions for editors that have the ability to convert tabs to spaces
    • Vim, Emacs, Nano, gEdit, Sublime Text (full version not free)

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *