2
PYTHON PROGRAMMING

THE MAJORITY OF THE PROJECTS IN THIS BOOK ARE WRITTEN IN THE PYTHON PROGRAMMING LANGUAGE, WHICH COMES PREINSTALLED WITH THE RASPBIAN OPERATING SYSTEM. PYTHON IS A FAIRLY SIMPLE LANGUAGE TO LEARN, BECAUSE ITS STRUCTURE MAKES IT EXTREMELY USER-FRIENDLY. BUT IT ALSO HAS COMPLEX FEATURES SUITABLE FOR MORE ADVANCED PROGRAMMERS AND CAN ACCOMPLISH TASKS EFFICIENTLY.

When building the projects in this book, I’ll walk you through writing Python code for each program. As a result, you’ll learn the basics of the language as you complete the projects. Before we get started, we’ll look at some programming basics, such as printing statements, making choices, and avoiding common errors in Python.

EXPLORING PYTHON

To illustrate Python’s efficiency, imagine you’re writing the classic first program to display Hello World on your screen.

In the Java programming language, you would write this code:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World"); 
    }
}

In Python, you can achieve the same output with just a single line of code:

print ("Hello World")

Python code is written in an integrated development environment (IDE). An IDE is the software you use to write Python code, in the same way you might use a word processor to write a document or a web browser to load and view a website.

INTRODUCING THONNY AND IDLE

The Raspbian operating system comes preinstalled with access to a Python IDE named Thonny (Figure 2-1). This default Python editor includes a wide range of error-detecting and code-highlighting features. If you need to install Thonny manually for any reason, open the terminal and enter this command:

pi@raspberrypi:- $ sudo apt-get install python3-thonny

The Thonny IDE has a section for you to write full program code as well as a Shell. The Shell area is where you can write single lines of code and test them without having to save the full program code. You can read more about Thonny’s features at http://thonny.org/.

Image

FIGURE 2-1 Thonny, the default Python IDE

Python has other editors available, including IDLE (pronounced idol), the classic IDE for writing Python code. When you download Python onto something other than Raspbian, say your regular laptop, this is the editor that is supplied.

The program code for each project can be written in any Python editor, but IDLE has been used throughout this book and the code is colored to match it. If you want to use IDLE, open the terminal window and enter this code:

pi@raspberrypi:- $ sudo apt install idle3

You’ll find more information and download details at https://www.python.org/downloads/.

When you load IDLE, two windows will open (Figure 2-2). The window on the left is the Shell window. You can use this window to test single lines of code: when you write code and press ENTER, the code immediately runs. The Untitled window on the right lets you write and save multiple lines of code or full programs. Then you can return to them whenever you want to.

Image

FIGURE 2-2 IDLE is the classic IDE for writing Python code.

Once you’ve written your program, you’ll want to run, or execute, it to test that it works correctly. For both of the installed IDEs, you use the F5 key to save and execute a program. Most programmers write and test their programs as they’re developing them to catch and remove errors early in the process.

WRITING YOUR FIRST PROGRAM

Let’s write your first program, which will print a simple message to the screen. From the main menu, select the Programming option, select either Thonny or Python 3 (IDLE), and click FileNew. You can also click FileNew File from IDLE. At the top of your new window, enter this line exactly as shown (although you can change the text between the quotation marks to a message of your own if you want to):

print ("I can code")

To run the program, press F5 on your keyboard; you’ll be prompted to save the program. Click OK, and the program will save and run. The text I can code will appear in the Shell window.

Return to the previous window, and below your earlier code, enter this line:

print ("Look a second line!")

Once again, press F5 to save and run the program, which should now look like this:

print ("I can code")
print ("Look a second line!")

Now that you’ve written your first program, let’s review some Python basics.

STRINGS

Strings are a data type that represents text. You make a string by entering characters inside single or double quotes: either method works as long as you use the same type of quotes at either end of the string.

Inside the quotes, you usually enter text, such as "Welcome to Raspberry Pi Projects for Kids". You can print a string (display it onscreen), save it, and even manipulate it. You can also search strings for a particular word or character, measure the length of a string, and even replace a section of a string, all by using Python code.

Strings are not just for letters. They can also contain numbers and symbols. For example, the string "C3P0" contains letters and numbers. However, the numbers in a string have no value; they simply represent the symbol for the number 3 and the symbol for the number 0. Even a number by itself, such as "465", has no value, meaning you can’t use it as a number in your code by, say, adding it to another number.

Try it out: enter the following program, which looks like it should add two numbers:

Total = 500 + "500"
print (Total)

When you run this program, you’ll get an error. It won’t work because the program tries to add one number and one string, and strings don’t have a value. To solve this error, you need to remove the quotation marks from "500", which changes 500 from a string to a number. Both numbers now have a value, so you can add them together. Try running the program now.

VARIABLES

Some of the programs you’ll write will require the user to enter their own data into the code. Imagine a program that asks a player to input their name. Because this data will change for each user, you can store it in a variable. Think of variables as boxes inside the computer’s memory that hold information. You give each box a label so you can find it again.

In Python, you define a variable by first giving it a label, which is known as declaring the variable. For example, let’s use NameOfMyPet as the variable label. Next, you use the equal sign (=) to indicate that the variable contains a string or a value. The technical term for this is assignment, meaning you assign something to the variable. Finally, you state what the variable should contain. For example, the name of my pet is Iron Cat, so I could declare a variable like this: NameOfMyPet = "Iron Cat". The string "Iron Cat" is now stored in the computer’s memory, and I can retrieve it at any time by calling the variable NameOfMyPet. To print the contents of a variable, use the code print(NameOfMyPet):

NameOfMyPet = "Iron Cat"  
print(NameOfMyPet)

You can change the contents of the variable by editing the string. For example, you might change the pet name to Tony Bark. When you run the program after the change, the original contents of the variable are overwritten with the new pet name.

NOTE

You could use a variable label in lowercase style, such as nameofmypet. But this is harder to read and understand at a glance. Python programmers use a technique known as camel case: a capital letter indicates the first letter of each new word in the variable label (for example, NameOfMyPet).

You can also use variables to store user responses to questions, such as “What is your name?”.

To create a variable to store user input, you begin by declaring the variable. Then you use the equal sign (=) and add the question that you want answered or a prompt within parentheses on the other side of the equal sign. Delete the contents in your IDLE or Thonny file, and enter the following:

name = input("What is your name? ")
print ("Welcome ", name)

The program stores the name that the user enters in a variable called name. When you run the program, it retrieves the name from the variable name, combines it with the word Welcome, and prints that on the bottom line. For instance, if your name was Sarah, it would print Welcome Sarah. You may notice that there is a deliberate space after What is your name? and Welcome. This ensures that words are separated by spaces. Otherwise, it will print something like this: WelcomeSarah.

LOOPS

In some of the projects in this book, you’ll need your program to continuously repeat a set of instructions. For instance, in Chapter 3, the program needs to constantly check the level of light in the room to know when to trigger your hot glue night-light to turn on, meaning the code needs to keep running again and again. In Chapter 6, the trampoline program continuously checks whether you’re standing on a block of grass in Minecraft. If you are, it’s trampoline time, and you’re sent springing up into the air!

This programming technique is more commonly known as looping. The two types of loops are while loops and for loops.

while Loops

A while loop continues to repeat its code while a particular condition is met. The following example shows how you might use this loop:

 count = 5
 while count > 0:
      question = input("Do you like cheese? (yes or no) ")
     print ("")
     count = count - 1	

You set the value of the count variable to 5 to begin with. While the value in count is greater than 0 , the program asks the question "Do you like cheese? (yes or no) ". Then it prints a blank line to keep the layout looking neat and tidy. Each time the program loops—meaning each time the indented code after the while loop line runs—it subtracts 1 from the count value in the code count = count – 1 .

After the first time the loop runs, the new count value is set to 4. Because 4 is still bigger than 0, the loop runs again and, at the end of the loop, another 1 is subtracted. The program continues to loop until count reaches a value of 0. Then the loop stops, and the program ends. So this program will run five times and then stop. Notice that the lines at and are indented. Indentation indicates to the program that these three lines are part of the loop and run only while the loop is running.

When you use a while True statement, as shown here, the program will keep running until the user stops or closes the program:

while True:
    question = input("Do you like cheese? (yes or no) ")
    print ("")

Try it and you’ll be asked “Do you like cheese?” for eternity (well, at least until you exit the program).

for Loops

A for loop repeats its lines of code for a set number of times. In this example, the range value is set to 5, which means you’ll be asked whether you like cheese five times and then the loop will stop:

for x in range(5):
    question = input("Do you like cheese? (yes or no) ")
    print ("")

Notice that the for loop accomplishes the same task as the first while loop we created earlier. But it uses less code, making the program simpler and more efficient.

CONDITIONALS

Conditionals in Python let your program make decisions: when this is true, this happens, but when that is true, that happens. Think of conditionals like buttons: when you press one button, it makes a sound, but when you press another button, it flashes a light.

Conditionals let your code respond differently to various inputs or outputs. You create conditionals by using if, elif, and else statements.

An if statement is the start of the conditional and checks whether the first condition has been met. For example, if button A is pressed, play sound A.

If the first condition isn’t met, you can then check for conditions by using an elif statement, short for else if. This statement checks for the next choice if the previous choice wasn’t selected. In this example, if button A was not pressed, it might check whether button B was pressed. You can add as many elif statements as your program needs, checking for buttons C, D, and so on.

The last part of the conditional is the else statement. This tells the program what to do if none of the other conditions are met; in this example, if none of the buttons are pressed, the code in the else statement runs.

Consider the following program to see how conditionals work:

while True:
  question = input("Do you like cheese? (yes or no) ")
    print ("")
  if question == "yes":
       print ("Good choice")
  elif question == "no":
       print ("shame, I have lots spare")
  else:
        print ("Did you answer correctly?")
        print ("")

You begin by asking the user whether they like cheese . The user enters a response. You then use an if statement to check whether the user’s response is yes. If it is, the program prints the message Good choice.

If the user didn’t enter yes, the program skips to the elif statement to check whether the user said no. If they did, an alternative message is printed.

Finally, you use an else statement to respond to any answer that isn’t yes or no.

Enter the program and run it. You might want to try making your own examples.

FUNCTIONS

A function is a useful way to store multiple lines of code that perform a single task, like a set of instructions. Then, when you want to do that task elsewhere in your code, you just enter the function name rather than type all the code again.

To create a function, you enter def followed by the name of the function, a pair of empty parentheses, and a colon (the colon is very important!). Then press ENTER to move to the next line so you can type the instructions that the function will run. Notice that when you press ENTER, the cursor appears indented, not at the start of the line. As with loops, code lines that belong to a function need to be indented so Python knows they belong to the function.

To run the function at any point in the program, you write the function’s name followed by the empty parentheses. This is known as calling a function, as shown in the following example:

def PocketMoney():
    money = good_behavior * rate
    tax = (good_behavior  / 100) * 20
    print (money)
    print (tax)
good_behavior = int(input("Please enter the number of days you were
good "))
rate = float(input("Please enter your pocket money rate " ))

You begin by defining a function named PocketMoney(). The indented lines following the function definition calculate the amount of pocket money the user gets paid and how much they owe for “tax” based on information that the user inputs.

If you ran this program now, it wouldn’t do anything because you haven’t called the function; you’ve just defined it. The completed program, including the function call, looks like this:

def PocketMoney():
    money = good_behavior * rate
    tax = (good_behavior  / 100) * 20
    print (money)
    print (tax)
good_behavior = int(input("Please enter the number of days you were
good "))
rate = float(input("Please enter your pocket money rate " ))
PocketMoney()

Now the program will ask the user to enter the number of days they were well-behaved and how much pocket money they were paid per day. Then it calculates and prints the user’s final amount of pocket money minus an amount for tax!

RUNNING PYTHON CODE FROM THE TERMINAL

Sometimes, you’ll need to run a program from somewhere other than IDLE or Thonny. For example, you might run a program remotely from another computer, or you might not have a screen attached to your Raspberry Pi (as in the nature box project in Chapter 11). In such cases, you can run programs from the terminal. Doing so frees up the processor, RAM, and graphics for the Python program.

To run a program from the terminal, open the terminal and use it to navigate to the folder that holds the program you want to run. Then enter the following command:

pi@raspberrypi:- $ sudo python3 name_of_the_program.py

Replace name_of_the_program.py with the name of your Python program, and it will run!

NOTE

When I show code that you should run in the terminal, I’ll precede it with the prompt, which looks like this: pi@raspberrypi:- $. But you need to enter only the commands that come after the prompt, not the actual prompt.

COMMON PROGRAMMING MISTAKES

Programmers love to say that programming is 20 percent coding and 80 percent debugging, which is the term for correcting errors in your code. The word bug dates back to the days when computers were so big that they filled several rooms. The story goes that on September 9, 1947, a now famous programmer by the name of Grace Hopper realized that the computer had stopped working. When she inspected the computer, she discovered that a moth had gotten trapped between some of the moving parts. Hopper subsequently stuck the moth in her log book and wrote, “case of bug being found.”

Errors, bugs, and mistakes will cause your program to run incorrectly, stall, or not even start. Adopting a methodical, line-by-line approach to debugging will make the process easier. But be prepared to spend a lot of time looking for one small error. Hopefully, you won’t find a moth.

Many common mistakes are syntax issues. Syntax is a set of rules that govern how you must write your code. For example, a line of code inside a conditional must always end with a colon. Different programming languages use different syntax. When presented with errors, first check that you used the correct syntax. Two common syntax issues are the misuse of letter case and indentation.

Capital Letters

One of the most common syntax errors is using uppercase and lowercase letters incorrectly. Programming languages don’t always follow standard English grammar rules. Some lines of code begin with a lowercase letter, and sometimes a word might appear to have a random capital letter in the middle of it. Python is sensitive to the use of capital letters! Don’t try to correct what might look like a mistake but isn’t; you must enter the code in this book exactly as it’s shown.

For example, consider the following two lines of code:

Print ("Hello there")

and

print ("hello there")

Only one of them works. Which do you think it is? Try them both to see whether you’re right.

Indentation

Another common cause of error is indentation—the number of spaces at the beginning of a line of code. In general, it doesn’t matter how many spaces you use to indent your lines in Python, as long as you’re consistent. A good practice is to always leave four spaces, or one tab, for each indentation. You can use either, but ensure that you’re consistent and use only one method in your program. Don’t use both methods in the same program. As an example of correct indentation, consider this code snippet from the next chapter:

while True:
  print(ldr.value)
  time.sleep(2)
  if ldr.value <= 0.4:
     print("light on")
     led.on()
  else:
     led.off()

The lines at , , , and are aligned. So are the lines at , , and . This program code is indented properly, so it will run.

Recall that you need to indent code lines when you’re using conditionals and loops and when you’re defining functions. More generally, anytime a line ends in a colon, the following line or lines must be indented. If your indentations don’t align properly, your program will fail and produce an error message, as shown in Figure 2-3.

Image

FIGURE 2-3 If your code contains a syntax error, it will produce an error message like this one.

For example, this program has indentation errors:

while True:
     print(ldr.value)
     time.sleep(2)
  if ldr.value <= 0.4:
     print("light on")
            led.on()
        else:
               led.off()

Can you figure out which lines are incorrectly indented and will cause an error?

When you want an event to happen outside a loop or after a conditional, the code must be dedented, or realigned in line with the code before the start of the loop or conditional. For example, if you added a print statement at the end, but it was in line with the if statement , the if statement would also run this print command.

To read more about indentation, see the official Python website at https://www.python.org/dev/peps/pep-0008/#indentation/.

USING COMMENTS

When you finish a program and you look back at it later, you might find sections of the coding confusing, even though you wrote it. To help you and others understand what your code does, you can use comments. A comment is a note that gives the reader information about a section of code.

Python provides two methods for adding comments. The first is to use the hash mark (#). Usually, you’ll use one hash mark in front of the comment, like this:

print ("hello") # this is a comment

The second way to create comments is to use three single quote marks to open a comment and three to close it, like this:

print ("hello") '''this is also a comment'''

Remember that comments aren’t commands; they won’t execute when you run the program. Their only purpose is to provide a description and reminder of what the code does. So, which comment method should you use? If the comment is a single line, use the # option. If the comment spans more than one line, use the ''' method.

WRAPPING UP

With this brief introduction to Python, you’re now ready to start the book’s activities. Each chapter walks you through one complete project. You can complete the projects in any order, although they get progressively more challenging. You can also sample code, techniques, and elements from each chapter to invent your own customized hacks. For more guidance, check out the Raspberry Pi Foundation’s website and help forums.

Let’s start a project!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.97.170