Programming Guidelines for Python

This page contains a list of Python 2.7 guidelines that can make the life of students easier for the homework assignments. Consider seriously to use them as they can reduce the amount of work significantly ;)

Getting Started

The basics of Python programming are very nicely covered on this online tutorial. We recommend to use the IPhyton notebook.

Modules

There are several modules that you should use, as they already include multiple necessary functionalities.

  • For scientific computing, the numpy module is extremely useful as it provides N-dimensional array objects, useful linear algebra operations...
  • For producing figures with your results, the matplotlib module allows the use of 2D and 3D plots, plot property editing, figure saving to pdf...

Figures

  • Since saving figures takes time, a nice trick is to have figures being save automatically. An example where a multi-figure pdf is created can be found here.
  • When submitting a plot for an assignment, the plot needs to be readable and it should also look nice (at least it should not hurt the eyes). Always use a proper font size, correctly label your axes, zoom on interesting parts if necessary. For different curves in the same plot, use different line styles and colors.
  • An easy function for generating plots with mean and standard deviation is this (matplotlib.fill_between).
  • Do not put too many curves in the same plot!
  • This is a nice tutorial about matplotlib.

Coding Conventions

  • Program your code as modular as possible. Never copy paste code, but implement reusable parts in functions.
  • Use meaningful names for your variables, ideally consisting of several words in underscore_case.
  • Avoid functions with many (more than 4-5) input and output parameters. If you need so many, try to use structures.
  • Never use global variables! Its a sin and you will go to hell.

Learning to code in Python if you are a Matlab user

As numpy covers most of the standard functionalities of Matlab, a guide for Matlab users is provided in the scipy webpage.