Python Programming Tutorial: Getting Started with the Raspberry Pi

Pages
Contributors: Shawn Hymel
Favorited Favorite 30

Programming in Python

The bulk of this tutorial focuses on controlling hardware connected to the Raspberry Pi. To accomplish that, we will be using the Python programming language. As such, you should be familiar with some of the basics of Python, including literals, variables, operators, control flow, scope, and data structures. Depending on your comfort level with Python, we recommend the following:

  • Not familiar: Read the recommended documentation and attempt the challenges
  • Somewhat familiar: Attempt the challenges and refer to the documentation when you run into trouble
  • Very familiar: Feel free to skip this whole section!

Since we don't want to reinvent the wheel (there are many great tutorials and books out there on Python!), we will be referencing two texts:

  • A Byte of Python - A free, well-written introduction to the Python language. Concepts are covered briefly and succinctly with examples. Paper copies can be found here for purchase (besides, it helps support the author!).
  • The Python Documentation - A more technical and in-depth look at the Python language, which consists of a set of tutorials and reference guides. Refer to this if you need additional help understanding a concept.
Note: Some of the links for "A Byte of Python" might not open to the correct location on the page for some browsers. If this happens, just refresh the page to take you there.
Try it! Each of the code examples given can be run as separate programs. Try typing them out into the interpreter or copying them into a file (one example at a time) and running them with Python!

If you would like additional help with programming in Python (more examples and exercises) than what's provided here, check out the following free sites: Non-Programmer's Tutorial for Python 3, learnpython.org, and Google's Python Class. After covering the basics of the Python language in this section, we're going to dive into flashing lights, reading sensors, and controlling motors!

Comments

A comment is any text to the right of the pound (or hash) symbol #. The Python interpreter ignores this text, and it can be useful for writing notes to yourself or other programmers about what's going on in the code.

Example:

language:python
# This is a comment and is not seen by the interpreter
print("Hello, World!")

Recommended reading:

Literals

Literals, also known as literal constants, are fixed values and include integers (e.g. 42), floating-point numbers (e.g. 6.23), and strings (e.g. "Hello, World!"). Note that strings need to be in between single quotation marks (' ') or in between double quotation marks (" ").

Example:

language:python
print(42)
print("hi")

Recommended reading:

Challenge: Change the print("Hello, World!") program we wrote earlier so that it prints out your name.

Variables

Variables are containers whose values can change. We can store a number or string in a variable and then retrieve that value later.

Example:

language:python
number = 42
print(number)

Recommended reading:

Challenge: Store your name in a variable and then print that variable's value to the terminal.

Logical Lines

So far, we've been writing one expression per line in our program. For example:

language:python
message = "hello!"
print(message)

You can combine these two lines into one line by separating them with a semicolon ;:

language:python
message = "hello"; print(message)

These two programs will execute in exactly the same fashion. That being said, it's often recommended that you write programs with one logical line per physical line to make your code easier to read.

Recommended reading:

User Input

You can ask a user to enter information into the terminal by using the input() function. This will prompt the user to type out some text (including numbers) and then press enter to submit the text. Upon submission, the input() function will read the text and then return it as a string, which can be stored in a variable.

Whatever is in between the parentheses (known as arguments) will be printed to the screen prior to accepting user input.

Functions are sections of code that can be called by name. For example, print() is a function that takes the arguments and prints it out to the terminal. Notice in the example below that we separated two different arguments in print() by a comma. In this case, print() will print the different strings (or variables) in order on one line.

Note that you can use the int() function to turn a string into an integer (assuming the string is an integer).

Examples:

language:python
message = input("Type a message to yourself: ")
print("You said:", message)


number = int(input("Type a number:"))
print("You entered:", number)

Recommended reading:

Challenge: Write a program that asks for the user's first name and last name (two separate input() calls) and then prints the user's first and last name on one line. An example of this program running should look like:

User input in Python

Indentation

White space (number of spaces) at the beginning of a line is important in Python. Statements that form a group together must have the same level of indentation (amount of white space in front of the line). This will be important when we get into control flow statements (e.g. if, for) and functions.

If you have written programs in other languages before, you might be familiar with curly braces {}. In other languages, code in between these curly braces would form a group (or block) of code. In Python, a group (or block) of code is designated by the level of indentation of the individual lines of code.

Example:

language:python
answer = "yes"
guess = input("Is the sky blue? ")
if guess == answer:
    print("Correct!")
else:
    print("Try again")

if statements will be covered later, but note how the print() functions are indented, and thus form separate code groups underneath if and else statements.

Recommended reading:

Operators

An operator is a symbol that tells the interpreter to perform some mathematical, relational, or logical operation on one or more pieces of data and return the result.

Mathematical operators perform basic math operations on numbers:

Operator Description Example
+ Adds two numbers 2 + 3 returns 5
- Subtracts one number from another 8 - 5 returns 3
* Multiplies two numbers together 4 * 6 returns 24
** Raises the first number to the power of the second number 2 ** 4 returns 16
/ Divides the first number by the second number 5 / 4 returns 1.25
// Divides the two numbers and rounds down to the nearest integer (divide and floor) 5 / 4 returns 1
% Divides the first number by the second number and gives the remainder (modulo) 19 % 8 returns 3

Logical operators compare two numbers and returns one of the Boolean values: True or False.

Operator Description Example
< True if the first number is less than the second, False otherwise 5 < 3 returns False
> True if the first number is greater than the second, False otherwise 5 > 3 returns True
<= True if the first number is equal to or less than the second, False otherwise 2 <= 8 returns True
>= True if the first number is equal to or greater than the second, False otherwise 2 >= returns False
== True if the first number is equal to the second, False otherwise 6 == 6 returns True
!= True if the first number is not equal to the second, False otherwise (not equal) 6 != 6 returns False

Compound logical operators require Boolean inputs and give a Boolean answer.

Operator Description Example
not Gives the opposite (True becomes False and vice versa) x = False; not x returns True
and Returns True if both operands are True, False otherwise x = True; y = False; x and y returns False
or Returns True if either of the operands are True, False otherwise x = True; y = False; c or y returns True

Bitwise operators perform binary operations on the bits (1s and 0s) of the given numbers. This tutorial talks more about binary and bitwise operations.

Operator Description Example
& Returns a 1 in each bit position for which the corresponding bits of both operands are 1 (bitwise AND) 3 & 5 returns 1
| Returns a 1 in each bit position for wich the corresponding bits of either or both operands are 1 (bitwise OR) 3 | 5 returns 7
^ Returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1 (bitwise XOR) 3 ^ 5 returns 6
~ Inverts the bits in the given number (bitwise NOT) ~5 returns -6
<< Shifts the bits of the first number to the left by the number of bits specified by the second number 5 << 2 returns 20
>> Shifts the bits of the first number to the right by the number of bits specified by the second number 5 >> 2 returns 1

Recommended reading:

Challenge: Ask the user for two integers, and print the addition, subtraction, multiplication, division, and modulo of those numbers. For example, if you enter the numbers 6 and 7, the output should look like:

First number: 6
Second number: 7
13
-1
42
0.8571428571428571
6

Control Flow

The Python interpreter executes statements in your code from the top to the bottom of the file, in sequential order. That is unless, of course, we employ some time of control flow statements to break this normal sequential flow.

We introduce the range(x, y) function in the examples below, which generates a list of numbers between the first number, x (inclusive), and the second number, y (exclusive).

Statement Description Example
if elif else If a condition is true, execute the block of code underneath the if statement. If not, see if the condition is true in one or more else if (elif) statements. If one of those is true, execute the code block under that. Otherwise, execute the code block underneath the else statement. elif and else statements are optional. number = 42
guess = int(input("Guess a number between 1-100: "))
if guess == number:
    print("You win!")
elif guess < number:
    print("Nope")
    print("Too low")
else:
    print("Nope")
    print("Too high")
print("Run the program to try again")
while A while loop executes the block of code underneath it repeatedly as long as the condition is true. counter = 15
while counter >= 5:
    print(counter)
    counter = counter - 1
for..in Iterate over a sequence of numbers or objects. The variable declared in a for loop assumes the value of one of the numbers (or objects) during each iteration of the loop. for i in range(1, 11):
    print(i)
break Use the break statement to exit out of a loop. while True:
    message = input("Tell me when to stop: ")
    if message == "stop":
        break
    print("OK")
continue The continue statement works similar to break, but instead of exiting the loop, it stops the current iteration and returns to the top of the loop. for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Recommended reading:

Challenge: Write a program that prints integers counting up from 1 to 20, except that for every multiple of 3 (3, 6, 9, etc.), the word "fizz" is printed instead. The output should look like the following:

Counting and replacing numbers in Python

Functions

Functions allow you to name a block of code and then reuse that code by calling its name. You can pass data to a function through variables known as parameters (note that the variables in the function definition are called parameters whereas the actual data itself being passed are known as arguments). Data can also be passed back to the calling statement using the return statement.

An example of a function definition would look like:

language:python
def functionName(parameter1, parameter2):
    # Code goes here

You can call this function elsewhere in your code with functionName(argument1, argument2).

Note that variables declared inside the function definition are known as having local scope. This means that they cannot be accessed outside of that function. Variables declared at the top level of the program (i.e. outside any functions, loops, or classes) are known as having global scope and can be accessed anywhere in the program (including inside functions).

Important: Any functions you create must be defined before you use them! If you try to call a function higher up in the code (before its def definition), you'll likely get an error such as:

language:python
NameError: name 'FUNCTION_NAME' is not defined

Python has a number of built-in functions that can help you (we've already seen three: print(), int(), and range()). A list of these functions can be found in the Python Tutorial.

Example:

language:python
def add(x, y):
    sum = x + y
    return sum

print(add(2, 3))

Recommended reading:

Challenge: Starting with the code below, implement the sumTo() function that takes an integer as a parameter (n), sums all the whole numbers from 1 to n (including n), and returns the sum. You may assume that the input, n, will always be a positive whole number (do not worry about handling negative numbers).

language:python
def sumTo(n):
    # YOUR CODE GOES HERE

# Should be 1
print(sumTo(1))

# Should be 45
print(sumTo(9))

# Should be 5050
print(sumTo(100))

Objects

We have not talked about objects yet, but in reality, you've been using them all along. The secret to Python is that everything is an object. That's right: everything, including functions and integers.

An object is simply a collection of data stored somewhere in your computer's memory. What makes an object special in a programming language is the ability for it to store information and perform actions. We've already seen an object's ability to store data (for example, a = 3 means that a is an integer object and stores the information 3). But how do we get an object to perform an action?

Objects are given a set of functions as defined by their class, which acts as a blueprint--telling the objects what they can and can't do or information it can and can't hold. When we talk about functions within a class (or objects), we call them methods.

For example, we can test if a floating point number is an integer by using the built-in is_integer() method. Note that this method is only accessible from float objects! We can't call is_integer() on its own, so we use the dot-notation (.) to have the float object call the is_integer() method from within itself.

Example:

language:python
a = 3.0
b = 7.32

print(a.is_integer())
print(b.is_integer())

Note that we can't use an integer as a float! For example, if we said c = 8, then c is an integer, not a float! If c is an integer, there is no .is_integer() method in integers, so calling c.is_intger() would fail (and throw an interpreter error). Try it! To force an integer value to be a floating point number, we simply add .0 after it (just like we did with a = 3.0).

Recommended reading:

Challenge: Modify the code below so that the phrase stored in my_string is converted to all lower case letters and printed to the terminal. Hint: review the String Methods in the Python Reference Guide to find a built-in method to do this for you.

language:python
my_string = "THiS iS A TEst!"

# Should print "this is a test!"
# YOUR CODE GOES HERE

Data Structures

In addition to variables and objects, Python has four other ways to store data: list, tuple, dictionary, set. These structures hold a collection of related data, and each of them has a slightly different way of interacting with it.

Structure Description Example
List A list is a sequence of ordered items. You can access items in a list using brackets [] and an index (e.g. list[2]). Note that indeces are 0-based, which means list[0] will access the first item in the list. Because lists can be modified, they are known as mutable. my_list = [1, 5, 73, -3]
my_list[2] = -42

# Get third item in list
print(my_list[2])

# Get all but first item in list
print(my_list[1:])
Tuple A tuple works just like a list (an ordered set). The difference is that a tuple is immutable, which means you cannot change the values once they are set. A tuple is usually specified by parentheses (). While the parentheses are not necessary, they are highly recommended to make your code easier to read. my_tuple = ("bird", "plane", 5, "train")

# Get one item from the tuple
print(my_tuple[0])

# Get a tuple of second and third items
print(my_tuple[1:3])

# Can't do this because tuples are immutable!
my_tuple[1] = "skyscraper"
Dictionary A dictionary is a collection of assciated key and value pairs. Similar to how a phonebook works: you look up someone's name (key) and you find their phone number (value). Dictionaries are defined by curly braces {}, and key/value pairs are separated by a colon :. Dictionaries are mutable. my_dictionary = {"name": "Bruce", "aka": "The Hulk"}
my_dictionary["name"] = "Banner"
print(my_dictionary["name"])
Set A set is a mutable, unordered collection with no duplicate elements. Sets are optimized for determining if an item is in the set (and you don't care about the order of items). Sets are great if you want to implement any sort of set theory in Python. my_set_1 = set(["orange", "banana"])
my_set_2 = set(["apple"])
my_set_2.add("orange")

print(my_set_1)
print(my_set_2)
print("apple" in my_set_2)
print("strawberry" in my_set_2)
print(my_set_1.union(my_set_2))
print(my_set_1.intersection(my_set_2))

Recommended reading:

Challenge: Starting with the code below, implement the average() function to compute the average of the numbers given to it in list form. Hint: you will probably want to use the len() function.

language:python
def average(num_list):
    # YOUR CODE GOES HERE

# Should print 5.0
list_1 = [4, 7, 9, 0]
print(average(list_1))

# Should print 4.406333333333
list_2 = [-3.2, 6.419, 10]
print(average(list_2))

# Should print 42.0
list_3 = [42]
print(average(list_3))

Modules

Modules are another way to reuse code and help you organize your program. They are simply files that are imported into your main program. After importing a module, you can use a module in much the same way you would an object: access constants and functions using the dot-notation.

Example:

Save the following file as stringmod.py:

language:python
a = 42

def string_to_list(s):
    c_list = []
    for c in s:
        c_list.append(c)
    return c_list

In the same folder as stringmod.py, run the following code (either in the interpreter or saved as a file):

language:python
import stringmod

s = "Hello!"
print(stringmod.a)
print(stringmod.string_to_list(s))

Recommended reading:

Challenge: Python comes with several standard modules that you can import into your program. One of them is the math module, which you can use with import math. Use the constants and functions found in the math module to perform the following actions:

  • Print the ceiling of 3.456 (should be 4)
  • Print the square root of 9216 (should be 96.0)
  • Calculate and print the area of a circle whose radius is 2 (should be 12.566370614359172)

Finding and Fixing Bugs

Programs almost never work right away, so don't sweat it! The art and science of finding and fixing problems in your code is known as debugging. The most helpful debugging tool is the standard Python output. If there is a problem with your code, it will likely tell you where the error is and what's wrong with it.

For example, let's take the following code snippet. In it, we forget to indent our code underneath our for loop.

language:python
a = [1, 2, 3, 4]

for n in a:
print(n)

If you run this code, you'll see that the Python interpreter is super helpful by saying it was looking for an indented piece of code around line 4.

language:bash
  File "test_01.py", line 4
    print(n)
        ^
IndentationError: expected an indented block

Here's another example. Can you spot the error?

language:python
a = [1, 2, 3, 4]

for n in a
    print(n)

We forgot the colon after the for loop! The interpreter will let us know by telling us:

language:bash
  File "test_01.py", line 3
    for n in a
             ^
SyntaxError: invalid syntax

"Invalid syntax" is a little vague, but it tells you to look around line 3 for something that might be wrong, such as a missing colon, too many parentheses, a single quote instead of a double quote, etc.

What happens if your code runs, but it doesn't output the value(s) you expect? This is on you, the programmer, to find and fix! Adding print() statements throughout your code can help you identify where something might have went wrong.

Try running this code:

language:python
for i in range(1, 10):
    if i == 10:
        print("end")

Why don't you see "end" appear in the terminal? To help diagnose this problem, we can add a print() statement to see what's going on:

language:python
for i in range(1, 10):
    print(i)
    if i == 10:
        print("end")

When we run this, we see the values of i printed in order.

Using print() to debug in Python

A-ha! It turns out that i never reaches 10. That's because the second number in the range() function is exclusive. If we need it to count to 10, then we should change it to:

language:python
for i in range(1, 11):
    if i == 10:
        print("end")

Thanks for the help, print()!

Recommended reading:

Challenge: Find the 7 errors in the program below. When you fix the errors and run it, it should print numbers from 1 to the first argument, replacing multiples of the second argument with the word "buzz".

language:python
print("Count to 7, buzz on 2's")            
buzz(7, 2)

print('Count to 10, buzz on 5's")
buzz(10, 5)

def buzz(n):
    for i in range(1, n):
        if i % z = 0:
            print("buzz")
        else
            print(n)

Here is the program running successfully:

Output of counting with replace in Python