In the coming months you will learn to write a lot of code in Python yourself. Many of these tasks are general and would be repetitive if you wanted to implement them entirely in your own code. In this tutorial you’ll learn how to use execute code written by other people, so you can focus on the things that are most interesting for you.
In this tutorial you will learn how to:
- Start a Python interpreter
- Run a script
- Import and use external code
Review: Using Python
If you attended FSE 2016 you’ve already written and executed code in Python. This section is a quick refresh of some of the things you learned and is designed to get you up to speed even if you couldn’t come to FSE 2016.
Python is Full Stack Embedded’s go-to language. There are several reasons for this:
- It’s easy to learn
- It can call low-level routines, letting you interact directly with sensors from a script or program
- Even though it’s easy to start with Python, its good design lends itself well to writing more complex programs
- A lot of material on Python is open source so you can learn from it
- The Python community places a lot of emphasis on good design, so if you’re looking for resources you’ll often find stuff that’s built well and is approachable
Python’s focus on good programming is so entrenched in the language’s design that you can find a poem about it in an Easter Egg hidden in the language itself:
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
But we’re getting ahead of ourselves – understanding this requires understanding a little bit more about using Python. We’ll get to that in a few seconds.
This tutorial will assume that you are working in a Linux system. The Python code you’ll see will work just as well in Windows or Macintosh as it will in Linux, but at Full Stack Embedded we work mainly with Linux. If you’re working with a Windows computer, you can install Python directly into your system or install it into a virtual machine that runs on top of your operating system. Otherwise, consider installing Linux next to Windows or just working on the Raspberry Pi!
Starting the interpreter
In order to execute code in Python – whether you are running a script that you saved to a file or just typing code into the terminal – you’ll need to start the Python interpreter. You can do this by executing the command
python. You’ll see something like this:
pi@raspberrypi:~$ python Python 2.7.12 (default, Jul 01 2016, 15:34:22) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
As you’ll remember from the previous tutorial, the top line is the command prompt. This is where the Pi is asking us to enter a command, which we did:
python. After hitting Enter, the next two lines tell us what version of Python we’re running and where we can find more information. The next line, which only shows
>>>, is the command prompt from inside Python. Here you can enter any line of Python code and it will be executed immediately (with the exception of nested code, such as for loops, if clauses, etc.). Try entering a few lines of code and seeing what happens. If you’d like more information, see our presentation on using Python in the course materials from FSE 2016.
In order to exit Python, you can either press Ctrl+D or use the function
Running a script
If you have a script saved as a file that you’d like to execute, just pass it as an argument to python when you’re starting the interpreter from the command line, like this:
pi@raspberrypi:~$ python my_script.py
This would execute the script
You can name your script anything you want, but if you use the file extension
.py it helps programs and people see at a glance that the file you’re referring to contains Python code.
Using external code
Oftentimes, you’ll use code that you didn’t write yourself. This isn’t cheating – many programs have to do things like open files, establish HTTP connections, etc. There’s no use in everybody implementing this on their own. Python’s philosophy says that you shouldn’t have to worry about these details – it comes “batteries included”, meaning that there are libraries for doing just about every basic task there is. You can read about the packages included in Python’s standard library here. That’s also a good place to look for general details about how Python works. As you can see, there are a lot of packages that can help you do just about anything – work with data stored in different formats, perform computations on times and dates, schedule events, collect data, do math, and much, much more.
The import statement
You can access external code by
importing it. Here are a few examples:
import x from x import y from x import y, z
Let’s take this apart. How does this work?
import keyword tells Python to take a package and expose the functions and objects it contains to the current session. They can then be reached by addressing the package’s namespace. This is easier to understand with an example:
>>> # Remember, everything after '#' is a comment. >>> # Python doesn't execute it - it's only informative. >>> >>> # The math package contains several math functions >>> import math >>> # Now we can use the math package to do some computations >>> math.log(9, 3) 2.0 >>> math.sqrt(9) 3.0
math package into the current session, which contains, among other things, the functions
sqrt. These compute the logarithm and square root of a number, respectively. They are accessed by invoking the
math namespace and using the
. operator to use an object inside of that namespace. Finally, the name of the function we want to use is entered, followed by parentheses, which include any arguments we want to pass to the function. The result the function returns is, as you can see, what would be expected.
If you are using a function from within a package frequently, like for example if you wanted to compute the square root of a lot of numbers in your code, it might be tedious to always have to reference the package it belongs to. You can get around this difficulty by importing the function directly into your namespace, like this:
>>> # This imports the object "sqrt" without importing "math" >>> # No other functions are imported >>> from math import sqrt >>> # You can also import multiple packages simultaneously: >>> from math import sqrt, log >>> sqrt(9) 3.0 >>> log(9, 3) 2.0
You can use as many import statements as you want. Generally, imports occur at the very top of a script, so that it’s easy to see what external dependencies the script has.
Now it’s your turn. Write some code that uses functions or classes available from the standard library. Remember, if you’re not sure how to use a given package, read the documentation (each exercise links to the relevant page) and look for examples. The standard library is very well documented and often has examples right next to the objects in question.
- Import the datetime package. Use the date class in order to compute how old you are. Hint: You can use the date.today method in order to easily get the current day. Try finding out how many years and days old you are. Here’s an example (this will be the only solution posted in this tutorial):
>>> import datetime >>> now = datetime.date.today() >>> # Let's see what that looks like >>> now datetime.date(2017, 2, 1) >>> birthday = datetime.date(1939, 10, 27) >>> birthday datetime.date(1939, 10, 27) >>> age = now - birthday >>> age datetime.timedelta(28222) >>> age.days 28222 >>> years = age.days / 365 >>> years 77
- Use the uniform function from the random package to generate 100 random numbers between -10 and 10.
- Use the shutil package to copy a file, rename a file and create a zipfile from a folder.
- Explore the other packages available in the standard library. Get a feel for what’s available and try experimenting with at least one other package available there – perhaps you’re interested in unit tests? Working with temporary files? Saving data between Python sessions? Sending emails? In Python, this is all set up for you ahead of time.
If you’re looking for further challenges, try reading about the following more advanced topics:
- How imports work, and how you can import your own code
- Installing new packages with pip
- Writing your own package that others can install and import