Raspberry Pi for N00bs – Scripting with Python

Although I prefer other languages, here´s a small tutorial to get you started with Python on your Raspberry Pi. The latest Rasbpian distribution already comes with Python so you don´t even need to install anything else. Actually, i even found 2 versions on my Raspberry, 2.7.3 when i just run “python” in the terminal and 3.2.3 with “python3”. Obviously, we will use python3 here.

The first script

Open a SSH connection to your Rapsberry PI, as explained in my article “Linux Basics” and move to a custom folder where you can create your scripts. I prefer “/home/pi/scripts” for that, because “/home/pi” is the default folder. A big advantage is that you don´t need to use “sudo” in that folder, because it is owned by the “pi” user anyway.

Putting in “python3” without a parameter will open the python shell where you can test simple calls and play around. This is not really what we want, so we use an editor to create a script file. I prefer “nano“, which shouuld already be installed on your Raspberry. Of course you can also use a Samba network share and work with your favourite editor in Windows, but we will create very small Python files so you don´t need a heavy environment:

nano test.py

The nano editor is easy to handle, as long as you know some Shortcuts. Those you see at the bottom of the editor are always used with CTRL – for example: CTRL+O for saving).

Let´s start with a very simple script, open nano as mentioned above and put in the following line of code:

print("hello python and stuff");

Now close nano with “CTRL+X”, you will get asked if you want to save the file. Obviously, you should answer with “y”.

Alright, the last step is to launch the Python interpreter with the filename as parameter:

python3 test.py

If everything is set up correctly, you should see “hello python and stuff” printed right after the interpreter call. But there is another common possibility to run a script, with a so called “shebang”. Open the Python file again and add the following line as the very first one:

#!/usr/bin/python3

print("hello python and stuff");

There is one more thing to do: You have to make the file “executable”, and with “l -la” you can review the file attributes. After that, you can start the Python script without the interpreter:

#change file attributes to executable
chmod +x test.py
#list files with attributes
ls -la
#start script
./test.py

Syntax Basics

Variables

You don´t need to define variables before using them, and the datatype of a variable can change:

#initialize variable as integer
x = 5
#change type to string
x = "test"
#change type to array
x = ['value1', 'value2', 'value3']

Side note: comments in Python have to begin with a hash sign (“#”).

Blocks/Indentation

Structuring code in Python is something special. There are no brackets to specify blocks of code, it´s all done with indentation. Here´s a small expample, mind the colon after the “if”:

if (x > 5) :
	print("test1")
	print("test2")
print("test3")

If x is bigger than 5, everything will get printed out. If not, it´s only “test3”.

Conditionals

Part of it is already covered in the code above, here´s how it looks like with a more advanced example:

if x > 5:
	print("x > 5")
elif < 0:
	print("x < 5")
else
	print("else block")

Yeah, that´s not a mistake. It is really called “elif”, not “elseif” or “else if” 🙂

Loops

Unfortunately, there is no for loop like in pretty much every other language. In Python, there is only the “for in” loop:

myArray = ["value1", "value2", "value3"]
for myValue in myArray:
    print("value: " + myValue)

The while loop looks a bit more familiar:

n = 100
i = 0
while i <= n:
	i += 1
	print("still not big enough")

Btw, there is no increment/decrement in Python, so instead of “i++” you have to use “i+=1”.

User Input

Reading a string from the command line is pretty easy with Python:

userInput = input("Say Something: ")
print(userInput)

Functions

Of course there are also functions in Python, they are created using “def”:

def myShinyFunction(param1, param2=5):
    return param1 + param2

The second parameter is optional and by default set to “5”.

Classes

Python is object oriented, so there are also classes. This is how they are defined:

class Konto:
	def __init__(self, param1, param2):
		self.__myPrivateVar1 = param1
		self.__myPrivateVar2 = param2

	def getVar1Function(self):
		return self.__myPrivateVar1

The “__init__” block defines the constructor. Private variables are defined with “__” before the name, no “private” label is needed. Public does not need any label at all. More about classes can be found here: http://docs.python.org/3.3/tutorial/classes.html


This article just covers the very basic of programming with Python, the official docs cover a lot more stuff if you seriously want to get started with Python: http://docs.python.org/3.3/index.html

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.