adventures with microcomputers prototyping with raspberry pi

3. Introduction to Python 3

Python is a general-purpose, interpreted, high-level programming language. The syntax of the language has been optimized to emphasize code readability, as well as brevity.


any character surrounded by quotes. Quotes must be balanced. In other words, I could say

a = 'test'
a = "test"
#but not:
a = 'test
#See the difference there?

Similarly, if we are going to declare a variable as a string, we have to use quotes.

a = test
#does not work because the word test is not defined.

Python allows for numerous manipulations to strings. More specifically, if we go back to our original example:

a = 'test'

We could use various operations on it to get various information from our variable containing the string 'test'.

For example:

In [4]: len(a)
Out[4]: 4

We could also say:

In [5]: type(a)
Out[5]: str    # str is short for string

Lastly, we can return a part of the string by doing the following:

In [6]: a[:3]
Out[6]: 'tes'

Similarly, we can see what other functions are possible with a by entering a.[TAB] into the terminal.

This is a good strategy for working with iPython in general. Any time I get a new package/module, the first thing I do (after importing it) is to type its name followed by a period and then tab.

From this list, we can type out any of the functions followed by a ? to see a brief description of what it does. For example:

In [7]: a.upper?
Type:       builtin_function_or_method
String Form:<built-in method upper of str object at 0x104488750>
S.upper() -> string

Return a copy of the string S converted to uppercase.

So let's convert our string, contained in the variable a, to a capitalized version of itself. Try this:

In [8]: a.upper()
Out[8]: 'TEST'

However, if you try this:

In [9]: a
Out[9]: 'test'

So, if we wanted to permanently change a, we could do this:

In [10]: a = a.upper()

In [11]: a
Out[11]: 'TEST'


There are two basic types of numbers: integers and floating point numbers (floats for short). Integers are any whole number (positive or negative), whereas floats are any number with a decimal point. Try this:

In [12]: a = 5

In [13]: type(a)
Out[13]: int


In [14]: a = 4.0

In [15]: type(a)
Out[15]: float

If you want to, you could now enter a.[TAB] to see what other methods a (the variable that now stores a floating point number [4.0]) has.

Assignment operator, more variables

In Python, = does not mean what you would normally think it does. Our previous example:

In [16]: a = 4.0

Means “assign 4.0” to the variable named a. This is why we cannot say the following:

In [17]: 5 = 6
  File "<ipython-input-17-6d9c0c29354b>", line 1
    5 = 6
SyntaxError: can't assign to literal

So a 6 can never be assigned (or put inside) a 5, so this line of code will always throw an error.

Variables must be assigned prior to their use, otherwise python throws an error because it does not understand what you want it to do.

Try this:

In [18]: x
NameError                                 Traceback (most recent call last)
<ipython-input-18-401b30e3b8b5> in <module>()
----> 1 x

NameError: name 'x' is not defined

Nonetheless, variables, once assigned (and therefore established as a particular type), can be converted to other data types. For example:

In [21]: a = 5

In [22]: float(a)
Out[22]: 5.0

Or similarly:

In [23]: a = 4.9

In [24]: int(a)
Out[24]: 4


A compound data type used to group together other values. A list is written as a series of comma-separated values (or items) between square brackets. They do not need to be of uniform type. For example:

In [25]: a = ['spam', 'eggs', 100, 1234]

In [26]: a
Out[26]: ['spam', 'eggs', 100, 1234]

Individual items in a list are referenced by their index, or position. We can reference individual items by entering the variable and the position (counting from 0) into the interpreter.

For example:

In [27]: a[0]
Out[27]: 'spam'
In [28]: a[3]
Out[28]: 1234
In [29]: a[:2]
Out[29]: ['spam', 'eggs']

Individual items/elements in a string can be rewritten as follows:

In [30]: a[1] = 2

In [31]: a
Out[31]: ['spam', 2, 100, 1234]

If we do not happen to know how long a particular string is, we can make the interpreter figure it out be calling len() on it:

In [32]: len(a)
Out[32]: 4

append and insert are the two most common ways to add an element to a list()

Insert Example

In [20]: h = [ 'this', 'is', 'a', 'list' ]

In [21]: h
Out[21]: ['this', 'is', 'a', 'list']

In [22]: h.insert(3, 'great')

In [23]: h
Out[23]: ['this', 'is', 'a', 'great', 'list']

Append Example

In [30]: h.append('certainly')

In [31]: h
Out[31]: ['this', 'is', 'a', 'great', 'list', 'certainly']

insert adds an element to a list() at index, append simply adds an element to the end of a list().

extend concatenates two lists and returns a new one:

For Example

In [31]: h
Out[31]: ['this', 'is', 'a', 'great', 'list', 'certainly']

In [32]: i = [ 'the', 'best', 'list']

In [33]: h.extend(i)

In [34]: h
Out[34]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

index allows one to search a list() by value

For Example

In [36]: h.index('certainly')
Out[36]: 5

This is helpful if you know what value you are looking for in a (potentially) gigantic list() but have no idea where it is specifically.

Removing Elements from a list

There are two basic ways to remove an element from a list(): pop and remove.

Using pop

In [8]: h = ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [9]: h
Out[9]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [10]: h.pop()
Out[10]: 'list'

In [11]: h
Out[11]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best']

pop() removes and returns an item from a list() at index. If no index is specified pop() removes and returns the last item of a list().

Using remove

In [37]: h
Out[37]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [38]: h.insert(2, 'is')

In [39]: h
Out[39]: ['this', 'is', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [40]: h.remove('is')

In [41]: h
Out[41]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

remove() gets rid of the first occurrence of value. In the above example, the value 'is' was removed at index 1. In order to remove the second occurrence of 'is' one would have to run h.remove('is') again.

if statements

Let's take a look at a nice example of a function that contains Boolean Logic (true or false datatypes)

x = int(input('please enter an integer: ') )

if x < 0:
    x = 0
    print 'negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'single'
    print 'more'

Quite a bit to talk about here. Let's break it down line by line:

  1. We called a statement that takes any input at the command line, converts it to an int, and assigns it to the variable x.
  2. After that, we start our test. If x is less than 0, set x to 0 and print the statement 'negative changed to zero'.
  3. Elif (means else if) x RETURNS 0, print zero. Else if x returns 1, print single. If none of those things are the case (the final else), print the string more.

Before you try to type this in, notice the whitespace. Python groups statements together (in functions like this one, or otherwise) via whitespace. The normal Python protocol is to use four spaces to denote the first line belonging to a previous one (the line under the first if statement), or you can use indents.

Try to enter this into your interpreter with a different input value (not 42).

for statements

Type this into your interpreter:

words = ['cat', 'widow', 'defenestrate']

for w in words:
    print w, len(w)

Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. So, the above function declares a list called words with three items: cat, widow, and defenestrate (all strings). Then, it says for w (used as an index here) in the list words print w (the item at that position and the length of that particular item). This is why we get the sequence of words with their string length returned. Upon completion of the for loop (when the loop has iterated over each item in the list) the loop terminates.


The last built in function to be concerned with, at a basic level, is the range function. Range generates lists containing arithmatic progressions.

For example:

In [33]: range(10)
Out[33]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


In [34]: range(5, 10)
Out[34]: [5, 6, 7, 8, 9]


A dictionary (or dict) is a built-in datatype in python. dicts consist of key/value pairs between curly braces.

For example:

d = {'name':'boris'}

The line above creates a dict with the key 'name' and stores it to the variable d. Entering d at the command line will return the entire dict.

In [9]: d
Out[9]: {'name': 'boris'}

To add a new key-value pair assign the new key a value at d. If the key is not already in use it will be added to d. If the key is already in use the new value will simply overwrite the previous one.

For Example

In [21]: d = {'name': 'boris', 'age': 40, 'hair':'bald'}

In [22]: d
Out[22]: {'age': 40, 'hair': 'bald', 'name': 'boris'}

In [23]: d['eyes']='brown'

In [24]: d
Out[24]: {'age': 40, 'eyes': 'brown', 'hair': 'bald', 'name': 'boris'}

In [25]: d['age']=60

In [26]: d
Out[26]: {'age': 60, 'eyes': 'brown', 'hair': 'bald', 'name': 'boris'}

Here a new key-value pair was added to d ('eyes' and 'brown') and the value associated with the key 'age' was updated to 60 (d used to list the 'age' of 'boris' as 40).

But what if you need to remove something from a dict? There are a few ways to do this: 1. del 2. pop

Using del

del deletes an item from a dictionary by key (or, more generally, removes a value at a specific index). It's probably the simplest way to get rid of something in a dict

In [19]: d = {'name': 'boris', 'age': 40, 'hair':'bald'}

In [20]: d
Out[20]: {'age': 40, 'hair': 'bald', 'name': 'boris'}

In [21]: del d['age']

In [22]: d
Out[22]: {'hair': 'bald', 'name': 'boris'}

So the value '40' has now been removed from the dict d at the index (or in this case, key) 'age'.

Using pop

In [28]: d.pop('hair')
Out[28]: 'bald'

In [29]: d
Out[29]: {'age': 40, 'name': 'boris'}

In [30]: d = {'name': 'boris', 'age':40, 'hair':'bald

In [31]: d.pop('hair')
Out[31]: 'bald'

In [32]: d
Out[32]: {'age': 40, 'name': 'boris'}

The main different between del and .pop is that .pop will return the value removed at index.

Quick Notes

  • dicts are not typed. It is very common to see a variety of datatypes in the same dict. One can even store a dict as a value inside of another dict.
  • dicts provide the ability to add and remove key/value pairs at any time.
  • dicts are unordered.