\(\def\dt{\Delta t}\)
\(\newcommand{\transpose}[0]{^\mathrm{T}}\)
\(\newcommand{\half}[0]{\tfrac{1}{2}}\)
\(\newcommand{\Half}[0]{\frac{1}{2}}\)
\(\newcommand{\norm}[1]{\left\lVert#1\right\rVert}\)
\(\newcommand\given[1][]{\:#1\vert\:}\)
UP | HOME

Python Introduction

Table of Contents

1 Python Fundamentals

This section contains quick descriptions of some of the most basic principles of the Python programming language.

Properties
Here are some of the most basic facts about the Python language
  • Python is an interpreted language – There is no compiling. The language runs an interpreter that on-the-fly converts your code into machine instructions. This is similar to MATLAB, Ruby, PHP, Lisp, and many others. It is different from C/C++/C# and Fortran.
  • Python is a strongly-typed language – variables all have types, and using the wrong type of variable in a function or operation may produce errors.
  • Python is object oriented – Everything is an object. Python is "very object oriented", even a simple integer is implemented as a class.
  • Python is case sensitive – A=2 and a=2 are assigning two different variables.
  • Currently there are two active, major versions of Python – Python 2 and Python 3. While Python 3 is technically the official version, its adoption has been slow. The two versions are not drastically different, and it is certainly possible to write code that will work in either version. We will likely use Python 2.7 throughout the entire program (it is default on Ubuntu 14.04 and 16.04).
Built-In Types
There are several types of variables that are already defined in Python. These are referred to as the Built-In Types.
Numeric Types
There are 4 basic built-in numbers, int, float, long, and complex. Python will try to guess what type you are trying to use if you are not explicit. For example a=2 will assign the variable a to be an int with a value of 2, and a=2. will assign a to be a float with a value of 2.
Booloean Type
Boolean types can either be True or False. Truth value testing will always return either True or False.
Sequence Types

There are seven different sequence types built in. The most-used sequence types are str, list, tuple. The following shows assignments of each of these types:

var_string = "hello world" # assign a string
var_list = [1,2,3] # list of integers
var_tuple = ('hi', 2) # mixed tuple

Each of these sequence types have unique built-in methods that such as sorting, searching, iterating, etc. Strings and tuples are "immutable". Meaning once they are defined, they cannot be modified in-place. Lists on the other hand are mutable. See the difference below.

In [1]: a = [1,2,3]

In [2]: a[1] = 5

In [3]: print a
[1, 5, 3]

In [4]: b = "yes!"

In [5]: b[0]
Out[5]: 'y'

In [6]: b[0] = 't'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-1b9a7b288a85> in <module>()
----> 1 b[0] = 't'

TypeError: 'str' object does not support item assignment

The Data Structures section of the official Python Tutorial provides a thorough description of common operations associated with these sequence types. Note that the other, less common sequence types are unicode, bytearray, buffer, and xrange.

Mapping Type

Python has a single mapping type called a dict or dictionary. A dict maps any hashable "key" to any arbitrary object. Dictionaries are often used for keyword arguments to functions and for providing meaningful names to collections of data (like a struct in C). Dicts are mutable and iterable. Here are a few examples:

In [1]: ndict = {'a':[2,3,5,6,7], 'b':'hello', 'c':('item1',1)}

In [2]: ndict.keys()
Out[2]: ['a', 'c', 'b']

In [3]: ndict.values()
Out[3]: [[2, 3, 5, 6, 7], ('item1', 1), 'hello']

In [4]: for key,val in ndict.iteritems(): print key, val
a [2, 3, 5, 6, 7]
c ('item1', 1)
b hello

In [5]: ndict['a']
Out[5]: [2, 3, 5, 6, 7]

In [6]: ndict['b']
Out[6]: 'hello'

In [7]: ndict['d'] = 'newitem'

In [8]: ndict.keys()
Out[8]: ['a', 'c', 'b', 'd']

In [9]: ndict.values()
Out[9]: [[2, 3, 5, 6, 7], ('item1', 1), 'hello', 'newitem']    
Getting Help
It is easy to get help directly in a running Python interpreter. You can use help(object), dir(object) to see the object's methods, or you can use object.__doc__ to see the documentation string for the object. If you are in IPython you can also use the object? or ?object.
Syntax
Here are a few common syntax notes.
  • Python doesn't use line termination (no semicolons at ends of line)
  • Comments start with #
  • Blocks of statements are specified by indentation level (most controversial part of Python)
  • Colons are used to signify the start of a new block. For example, the following is a valid for loop:

    for i in range(10):
        print i
    

    Notice that the print line is indented four spaces further than the for line, and that the for line ends in a colon.

  • Python uses = for variable assignment and == for equality testing.
  • Python supports increment and decrement (+= and -=)
  • Multiple assignments are allowed on one line (through tuple unpacking): a,b = 1,2
Builtins

Beyond many built-in types, there are also many built-in functions. They are all listed in the official documentation. You can also see them inside of a Python interpreter with:

import __builtin__
print dir(__builtin__)
Functions

Functions are defined with the def keyword. Required arguments are listed first, and optional arguments listed second. Optional arguments are identified by assigning a default value.

def test_func(a, b=None):
    print a
    if b is not None:
        print "received b",b
   return
Namespaces, Modules, Imports

External libraries and modules are used by using the import keyword. Python looks for these modules by looking in several places. If the interpreter encounters the statement import foomod then Python first looks for built-in modules called foomod. Then it looks for a file named foomod.py in a list of directories contained in the variable sys.path. Note that to see the contents of this variable you would first need to import the built-in sys module using import sys. The directories in sys.path come from several places: i) the directory containing the input script (or the current directory) ii) the PYTHONPATH environment variable; iii) a list of system-specific default search directories that were set when the Python interpreter is compiled. You can also import individual variables or functions using the syntax from foomod import testfunc. Sometimes you'll see the syntax from foomod import *. This is not recommended as it imports all functions, classes, and variables directly into the importing scripts context. This is bad because the module you are importing could easily have a function that shares a name with a function in your script. This collision could cause a seriously annoying debugging issue!

Imagine you have a script called foomod.py in your current directory with the following contents:

def test_function():
    print "Called Function"
var = 10

Then, see the following operations to see several different versions of import:

In [1]: import foomod

In [2]: foomod.var
Out[2]: 10

In [3]: foomod.test_function()
Called Function

In [4]: from foomod import test_function

In [5]: test_function()
Called Function

In [6]: import foomod as fm

In [7]: fm.var
Out[7]: 10

In [8]: var = 0

In [9]: print var
0

In [10]: from foomod import *

In [11]: print var
10   

For further information about modules and importing see the official Python Modules documentation.

2 Python Rules-Of-Thumb

Here are just a few rules that I like to use when writing Python code:

  • Try to adhere to formatting standards, especially regarding tabs/spaces. I generally try to adhere to the Google Python Style Guide and the official Python Style Guide (aka PEP8).
  • Always properly use the if __name__ == '__main__': to ensure that your script can either be executed by a Python interpreter, or imported by another script.
  • Python scoping can be complicated. Try to avoid using global variables and instead put variables inside of a class. Some people might disagree with this opinion, but I think it is helpful.
  • Always try to use Python packages that are installed via apt-get. Only install things from PyPi (using pip or easy_install) if you really need a newer version of something or if you need a package not available on apt-get. Debugging unintended imports can be very tricky.
  • Read, understand, and follow the Zen of Python (aka PEP20).
  • Check out the The Hitchhiker's Guide to Python for a great resource on how to write high quality Python code. The Code Style section is an especially valuable document.
  • When in doubt, test it out. Python is very fast to prototype. If you are unsure how a particular operation is going to work. Just test it to find out. When I'm developing a Python project, I often find myself creating many small test scripts to ensure the code I'm writing is always producing the behavior that I expect.

3 Useful Python Packages and Tools

IPython
This is a vastly improved interface to a standard Python interpreter. Features whitespace-aware pasting, integrated script execution, TAB completion and more.
Numpy
This is the number one module for advanced math and matrix operations.
Matplotlib
This is Python's main plotting library.
Scipy
Similar to Numpy but has extra mathematical tools such as curve fitting and numerical integration.
pyserial
This is a great library for communicating with serial devices.
flake8
This is a Python syntax checking tool.
sympy
This is a Python library for symbolic computation. It is very powerful, but certainly takes some practice to learn.
sphinx
A tool for automatically creating documentation for Python packages. Can be integrated with Read the Docs and GitHub to have online documentation built and hosted for free.
Enthought Canopy
Includes a complete standalone Python installation pre-bundled with many common packages, an IDE, and integration IPython. Not that useful on Linux (because it is so easy to install Python packages on Linux), but can be great on Windows. Also includes a built-in editor and IDE. Technically this is a paid program, but it is free for students.
Anaconda
Very similar to Canopy, but in my experience, more widely used.
PyCharm
PyCharm is a Python IDE that many students in the past have had success with. It is easy to use, free for students, and can easily be integrated with ROS. Check out these setup instructions if you'd like to give it a try.
Spyder
This is a full Python development environment with and IDE. I have never used this, but I know that students in the past have found this useful.

4 Helpful Resources

PyCharm Edu
The PyCharm team has a great set of interactive tutorials that walk you through the basics of Python.
Google Python Course
This is a great series of lessons that teach the basics of Python.
Learn Python the Hard Way
This is a book that can be purchased, or you can read the contents for free (minus video lectures) here. It is often pointed to as one of the best Python learning resources.
Official Python Documentation
The documentation for Python is very good, and it contains numerous useful examples for just about any Python concept. There are also a variety of Tutorials and HOWTOs. For those with no experience with object oriented programming, I'd highly recommend reading the tutorial on Python Classes.
Creative Commons License
ME 495: Embedded Systems in Robotics by Jarvis Schultz is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.