1. Introduction

Python 3 is a high-level programming language. It is interpreted, can be run directly from the command prompt without prior compilation, and thus excellent for prototyping. The language is used widely in engineering and the commercial world and ships pre-installed with many operating systems including Linux and macOS.

We will use it both for programming microcontrollers and the backend (Laptop, desktop). You can either install it on your own computer or get an account on the EECS Instructional Cluster and run Python there.

The most recent version of Python can be downloaded from python.org. At least version 3.6 is required. If you are not sure which version you have, open a terminal window (e.g. cmd.exe on Windows or terminal.app on macOS) and start the interpreter[1]:

> python3
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

3.6.5 is the version, and >>> the REPL prompt, indicating that the interpreter is waiting for Python instructions. E.g.

>>> # expressions
>>> 2**8
256
>>> '#'*9
'#########'
>>>
>>> # loops
>>> for i in range(3):
...   print("{}*{} = {}".format(i, i, i**2))
...
0*0 = 0
1*1 = 1
2*2 = 4
>>> # methods
>>> def factorial(n):
...   if n <= 0:
...     return 1
...   else:
...     return n * factorial(n-1)
...
>>> factorial(7)
5040
>>>
>>> # decimal, hex, binary ...
>>> n = 157208
>>> "{} = 0x{:x} = b{:b}".format(n, n, n)
'157208 = 0x26618 = b100110011000011000'
>>>
>>> # complex arithmetic ...
>>> import cmath
>>> cmath.exp(3j)
(-0.9899924966004454+0.1411200080598672j)

Type exit() to quit the interpreter.

2. Learning Python

Many online tutorials teach Python. For example, tutorialspoint has a comprehensive guide that is easy to navigate from a menu. For IoT 49 you should be familiar with all topics under Basic Tutorial and ready to head back whenever encounter a coding problem.

In addition to the Basics, you should also know about classes. Below is a simple commented example:


class Account:  (1)

    def __init__(self, name):    (2)
        assert name != None, 'Name must not be None'   (3)
        self.name = name         (4)
        self.balance = 0

    def deposit(self, amount):   (5)
        self.balance += amount

    def withdraw(self, amount):
        self.balance -= amount

    def __repr__(self):          (6)
        return "{} has a USD {} balance".format(self.name, self.balance)
1 Code for class declaration starts with class and a name
2 Initializer. Invoked from Account('Ann'). It’s a normal function, except indented (since it’s part of class Account) and the first parameter is always self.
3 Classes are often put into libraries and shared with others, so it’s good to do some error checking. The assert statement raises an exception if the condition is not met and prints the given error message.
4 Store name in class instance for later reference. Note the use of self. Without, name would be a local and forgotten after init returns.
5 These functions belong to the class. They “know” about all instance variables (name, balance in this example).
6 Tells Python how to display class, e.g. in print. Without repr, print would show something like <main.Account object at 0x10291f198>.

Use the class (from the Python REPL) as follows:

>>> a1 = Account("Ann")
>>> a1.deposit(20)
>>> a2 = Account("Paul")
>>> a1
Ann has a USD 20 balance
>>> a1.deposit(50)
>>> a1
Ann has a USD 70 balance
>>> a1.withdraw(20)
>>> a2.withdraw(5)
>>> a2.balance
-5
>>> a1
Ann has a USD 50 balance
>>> a2
Paul has a USD -5 balance
>>> a3 = Account(None)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<string>", line 78, in __init__
AssertionError: Name must not be None
If “nothing” works, verify that you did not forget self somewhere …​

The tutorial has more information about classes and how to use them.

3. Plotting

Python comes with excellent support for plotting. See https://matplotlib.org for installation instructions and documentation.

from pylab import *

def f(t):
  return cos(2 * pi * t) * exp(-t)

t = linspace(0, 5, 500)

plot(t, f(t))
plot(t, -exp(-t))
title("Damped exponential decay")
xlabel("Time [s]")
ylabel("Voltage [mV]")
legend(['oscillation', 'decay'])
N python 0

1. On some systems, Python 3 is started with python, others use python3. Just try to see what works or check the documentation of your installation for instructions on how to start the interpreter on computer.