empowering creative people

Videos / Raspberry Pi Workshop - Chapter 2 - Introduction to Python

The full Raspberry Pi Workshop in step-by-step format can be found here http://coreelec.io/piworkshop I've tried to squeeze in as many Python features as I could into this short script.

Search Videos

Related Content



Python is a high level programming language - what this simply means is that the code you write can closely resemble the english language which enhances readability. Along with the core functionality, Python supports using modules and packages which means that we can import specific functionality when we need it. You may have heard the phrase ‘object oriented programming’ before, well Python is an object oriented language. If you don’t know what this means don’t worry, it’s not particularly important - just keep it in the back of your mind.

In these workshops we’re going to be working with Python 3 on our Raspberry Pi. For a beginner the most noticeable differences between Python 2 and 3 are some syntax changes - that is the exact structure of the commands is slightly different between versions but that’s the most noticeable anyhow.

Coming over onto our desktop environment we can run Python by going to the applications menu, go to programming and going down to Python 3. This brings up the Python shell or IDLE and this is where we can kind of road test commands live. So, let’s give that a go, let’s create a variable, we’ll just call the variable ‘a’ and we’ll set it equal to 10 so we can recall ‘a’ by just typing a and that shows us the variable, the variable type and what it is. In this case we have an integer which is 10. We can do things like a equals a times a and if we call a again we have 100. We can even create strings so  we can say string is equal to some string, and I’m going to be particularly boring and choose hello world once again. Let’s have a look at what happens when we invoke string again - so we can see string which has hello world with some quote marks.

Now we can print text to the screen with the print command and we can print some text and that comes up just as one would expect and we can also print the variable string, so we can print string without quotation marks and we can see hello world is there.  So when we printed string it returned the variable type and what it is, that is it’s showing us that it’s a string by giving us these quote marks and then it’s showing us the contents of that variable. Whereas here print is for outputting information so it drops the quote marks because its printing just the contents of that string.

Now, in the supplementary material for  this course we have a script for  this section. I’ve already, in my files system created a directory for chapter 2 and inside that I’ve already copied that script. So what you might need to do is go to file, new file, and then you can type that script out into this window and save it. Make sure you save with a .py for Python extension.  So I’m going to open that script and we’re just going to have a quick walk though of a lot of the functions in there.  I’ve tried to cram as much as I can into this example so it’s quite heavy on just the little tricks and nuances that Python might have.  Let’s give this a run, I’ll just restart the shell, that’s useful just to clear it - no, that hasn’t worked. Never mind, I’ll just go down here so I’ve got a clean screen and we can run the script with run, run module or we can strike F5 and let’s have a look at what comes out. No worries, so what we have is a print and a string thats come up just as we might expect, we can use # for comments - this is to increase the readability of our code.  By putting in comments we can leave messages for ourselves or other programmers about what the code is doing in a more human readable form.  So we create 2 string variables called hello and world and in the next statement we can see that we are printing string 1 plus a space plus string 2 - so we’ve got hello, a space, and then world - and then we’re printing the string, just the exclamation point times 3 and we can see that that’s multiplied that string, or repeated it rather, 3 times.  So this is called string concatenation when we stick two things together.  We’re also repeating with the multiplication symbol, the asterix (*)  We can create a variable called 2 on 3 which is just equal to two thirds and in the next couple of lines we’re printing some variables in our print statement so we can say 2 divided by 3 is about and then these 2 kelley braces {}  they will allow us to insert information into that print statement. We do that with the dot format argument here, and in dot format we’re just using the variable 2 on 3 so what means is 2 on 3 will be substituted for these closed braces. The same thing happens on the next line except within the braces we can include formatting information and in this case we’re formatting the output as a float. So rather than punching out as much information as Python can about the variable 2 on 3 the default format for float appears to be about 6 decimal places and that’s the difference between those two commands.

Next up we have an import statement, so this is what I was talking about before when we can import functionality. In this case we’re importing a mathematics toolbox essentially. Math has a bunch of routines and constants for us to use which are going to be helpful later on.  Usually we put imports at the top of a script, that’s by convention but if you put the import at the top of a script you’ll never have commands above that import statement that rely upon it, so we usually put them at the top. I’ve just put it here to highlight where it’s being used. So we’re creating a string called more and in this very large print statement which I’m going to draw out so we can read fully.  We’ve got one, two, three variable being displayed and by including a number or an index inside these braces we can explicitly pick and choose which variables we’re pulling out of our format argument.  So if you swap the indexed you’ll swap which variable you’ll draw from so here we can see the output is you can print more than one variable here’s Pi, that makes 3 variables and the code for that has the string more for the zeroth variable then pi for the first and here is where our math toolbox came in handy. We have math.pi so here we’re invoking the pi constant from the math package and  that’s done by using this dot. So math is an object and we can access parts of that object with that dot. Then the last variable is just the number 3.  We can throw in a blank line in our output, that’s this - there’s a bit more space here. That is with the backslash /n character which is a special escape sequence to just do a new line. It’s like a line feed.

Now we’re going to do some looping, so this is going to be a FOR loop and we’re going to say for some variable num in range 2 to 10 incrementing by 2, so just to reiterate - we’re going to make up some variable called num and we’re going to allow it to take on the values in the range 2 to 10 but we’re going to increment it by 2 each time.  So that is quite a lot to handle but when we come down into the next line we can see that we’re indented by white space. Python uses white space for code structure so you need to make sure that that indentation is there. If you didn’t have the indent there you would have an empty FOR  loop - it also kind of forces you to keep your code looking good. Because if it looks good, it will run well. So inside this for loop the only line that we have is to print num and you can see that we get 2,4 , 6, 8 - we don’t get 10 because as the loop increments from 8 to 10 it’s reached the end of its range and it meets the condition that it is now outside the loop so it doesn’t for 10. We print another blank line and then we create an array - so an array is just a list, it doesn’t necessarily have to be of numbers, it could be of other things. You could even have an array of strings but in this case we have an array of numbers. So we have numbers incrementing from 1 - 7 and then decrementing down to 1. I’ll come back to why that was 15 in a moment. We’re going to use this array in the following loop. So this is a different loop, this is a different style of invoking a loop. We still have a FOR loop and we’re going to say FOR element in a - so ‘a’ is an array and an array has items in it or elements. So this is saying for every thing in ‘a’ run some code and then increment to the next one. Now within this FOR loop we come in and we indent and then we come straight up against an ‘IF’ statement and this is what we’re going to use to branch our logic - to make decisions.  Here we say IF the current element we’re looking at is equal to the maximum value in that array - in this case it’s going to be 7. So it’s essentially like saying IF element equals 7 then we do some stuff otherwise we’re just going to print element and we can use element to repeat this simple string which is just an equals sign. So, you might have already seen over here we have these equal signs counting from 1, 2, 3, 4, 5, 6, 7  and in fact I ran the old code so i’ll run it again 1, 2, 3, 4, 5, 6, 7 and then we reach the largest element which is the 7th so that is where this IF statement is true. We print another set of those equal signs, a message and then we leave the IF statement and we print that set of equal signs again and that creates a nice symmetric visual effect.

I encourage you to play with this script and just turn the knobs on it and just see how the output changes. One thing that I intended to show you is what happens if we make one of these elements much larger and also not in the middle. So if I make that 15 again and run the script we can see that it is not symmetrical and now the flag that’s telling us we reached the largest element is more towards the bottom so we kind of go up come down and then go up again and that’s exactly whats happening in this array.

 So that just about wraps up the basics, some very very basic commands in Python, these are going to be the building blocks that we create  larger projects with. We’re going to start using exactly this kind of code in the next section to start driving some hardware.