Sunday, January 27, 2013

Python on RaspberryPi 01

Learn Python. Starting at the beginning...
  
Note: This is a translation of the popular basic guide to Python on the Raspberry Pi: Python sur RaspberryPi 01 (in french), adapted where it made sense.

For the experts, there's not much to see in this article. For everybody else who keep seeing references to Python in your research on the Raspberry Pi, and wondering why they keep talking about a snake, then this article will be perfect for you. Or perhaps, you do know that Python is a programming language.

Welcome to our series of tutorials on the Python programming language, with a specific application to the Raspberry Pi.

Sites


Before we get too far, I want to provide you with a few basic links. The first is to python.org.

If you spoke another language, such as Spanish, Portuguese, French, Italian or Russian, I would point you to several other websites, because for other languages, individuals tend to have more complete sites than the official one (or, I should say, more in tune with the culture). But since you are reading this in English, python.org will become your primary stop.

There, you will discover regional user groups, documentation, downloads, mailing lists, a wiki and eventually, a Jobs section. You can't get enough of documentation? Then readthedocs.org

If you are the visual type, check out also pyvideo.org

Books


In english, there are lots of choices. In fact, too much. For example, on Amazon, you'll find over 1000 books on Python. Even checking out only hardcovers, you'll still end up with over 85 books!

If you live in a big city, it is a good idea to go to your local book store, and check out what books they have. As I've taught some Python to others, and recommended some books based on their personality, I've noticed that almost everybody is different. One book that I like, you might hate, and vice versa, because we are all different.

So you'll have to dig and see what book appeals to you, based on styles that vary from "Python for Kids", "Hello Python" and "Head on Python" to "Core Python Applications Programming" or even a "Python Essential Reference". There are many textbooks available too, some are assigned reading material for Python classes in colleges and universities, worth your time to check them out.

Free eBooks


I won't hold back in recommending some books in this section. Considering how much you will pay for them... the value to cost ratio is difficult to beat :)

Green Tea Press has several free ebooks. These are also available in print and eBooks from OReilly, for a fee. Among them is the classic text (or I should say the new edition of the classic text):

How to Think Like a Computer Scientist: Think Python

There is also Think Complexity

Moving on to another editor, for many years, Dive into Python was another recommended book. It is available to download for free.

In the not quite ebook, it is an online book category:
Learn Python The Hard way
A Byte of Python
Code Like a Pythonista: Idiomatic Python

If you are into games or young, or you want to help younger folks to learn Python, you might want to look at:

Invent With Python
Snake Wrangling For Kids

Have you found a free ebook that should be mentionned here? If so, please leave a comment!

Python, the program



So, Python is a programming language, but it is also an executable program. It is included with the Raspberry Pi and with most Unix type systems (Solaris, OpenIndiana, Mac OS/X and the varieties of Linux and BSDs ). It can also be installed on Windows, iPhone, iPad, Android etc. In this article, I will differentiate the python program from the language, by writing it in bold characters.

It is possible to use python in various ways or mode of operations.


First mode 

 

In an interactive way, from the command line:


pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 


The python shell is now waiting for a command, to have something to do. We will ask it to print the words "Raspberry Pi!". In the same way that I had to put quotes around the words to clearly differentiate what I want to print from the rest of the text, in Python it is required to delimit a string of characters (a sentence) with simple (') or double (") quotes on each side of this string:

pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Raspberry Pi!"



To simulate this in your browser (with Brython), click python answered us:
Raspberry Pi!



If our string of characters extends beyond one line, then we will have to use the single or double quote symbol, three times on each side ("""I'm writing a lot of words, so you better be ready for me with a multiline string, since I will go on and on and on.""")


pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print """
... Raspberry Pi!
... I continue.
... I am done!
... """

Raspberry Pi!
I continue.
I am done!



python answered us:
Raspberry Pi!
I continue.
I am done!

However, in our case, we are not done at all, we are barely starting! It is as good a time as any to mention at this point that a string that starts and ends with the triple quote ("""string of characters""") by itself, without instructions, is what is called a docstring, a string of characters (or sentence) for documentation purpose. A form of commentary, in other words.

We can also use python like a calculator:


pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 * 32
64


To exit the python program, we must type the commant: exit()
The word exit, followed by a pair of parenthesis, indicates that exit() is a function. We will come back to functions later on (and we will learn that print is a strange animal, that should be written print(), but that's for another time).

Second mode


If our code is quite short, there are no issues with using the interactive mode. But it might become burdensome to write the same code again and again. It's a good thing then that we can save our code in a file, whose name will end with the .py extension and that we can execute again and again.

Let's save our program that prints "Raspberry Pi!" in a file. In order to do that, we will need an editor. For the experts, I would recommend something like scribes in graphical mode and vim in console mode (text).

Since we are starting out, I would recommend instead to install geany:

pi@raspberrypi ~ $ sudo apt-get install geany
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  geany-common
Suggested packages:
  doc-base
The following NEW packages will be installed:
  geany geany-common
0 upgraded, 2 newly installed, 0 to remove and 134 not upgraded.
Need to get 3,401 kB of archives.
After this operation, 8,682 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://mirrordirector.raspbian.org/raspbian/ wheezy/main
 geany-common all 1.22+dfsg-2 [2,336 kB]
Get:2 http://mirrordirector.raspbian.org/raspbian/ wheezy/main
 geany armhf 1.22+dfsg-2 [1,065 kB]
Fetched 3,401 kB in 6s (518 kB/s)                                              
Selecting previously unselected package geany-common.
(Reading database ... 91199 files and directories currently installed.)
Unpacking geany-common (from .../geany-common_1.22+dfsg-2_all.deb) ...
Selecting previously unselected package geany.
Unpacking geany (from .../geany_1.22+dfsg-2_armhf.deb) ...
Processing triggers for hicolor-icon-theme ...
Processing triggers for man-db ...
Processing triggers for menu ...
Processing triggers for desktop-file-utils ...
Setting up geany-common (1.22+dfsg-2) ...
Setting up geany (1.22+dfsg-2) ...
Processing triggers for menu ...
pi@raspberrypi ~ $ geany raspberry.py


We just launched our editor, with a filename of raspberry.py. We type our code in the window raspberry.py:

Geany code editor

We save, and we quite (for right now, so as to keep things simple).

How can we run our raspberry.py script? Quite easily:


pi@raspberrypi ~ $ python raspberry.py
Raspberry Pi!
pi@raspberrypi ~ $ 

This is the second mode of operation, python running a script.

Third mode


The third mode is available on Unix type computers, and as such, on the Raspberry Pi. Let's bring up our geany code editor once more:

pi@raspberrypi ~ $ geany raspberry.py 
 
We insert a new line 1


We save after adding the new line, and we quite. The line we've just added to the script tells the operating system shell which program will run this code. In our case, we specify python.

That is not all, however. We also have to change the file from a document mode, to an executable mode. We do this through the chmod command:

pi@raspberrypi ~ $ chmod +x raspberry.py

We are now ready to launch our script directly:

pi@raspberrypi ~ $ ./raspberry.py
Raspberry Pi!
pi@raspberrypi ~ $

With a little help from my friend


Wouldn't it be nice if we didn't have to leave the comfort of our editor each time we wanted to run the program after making a change? We can do this through the use of the F5 key, or through the Build->Execute menu, or even using the button with the gears (View or Execute):

Raspberry Pi! - press return to exit that screen


This concludes our first basic tutorial on Python on the Raspberry Pi. I hope that this was sufficient to get you started.

@f_dion

3 comments:

  1. I like geany, but why dont you mention Idle ? It comes by default with Python so you dont need to install anything to start. Also it is at the same time a shell and an editor...

    ReplyDelete
    Replies
    1. I agree with Joaquin. You actually do NOT need anything but idle.

      Delete