Chapter 8

Get Started with Python

Computer experts enjoy creating new programming languages. While you literally have hundreds of languages to choose from, at any given time, only a few are popular.

This project introduces a popular language called Python. Unlike some programming languages, Python is easy to learn and use. But it’s also a real grown-up language used by grown-ups for real work. If you learn Python, you’ll be on your way to creating software you can sell.

image

Meet Python

Scratch is a good way to start learning about making computers do what you want, but it’s just a beginning. There’s a lot you can’t do with Scratch. For example, you can’t create your own desktop windows, search web pages for information, or send Tweets.

For bigger and smarter projects, you need a bigger and smarter way to give your computer instructions, which you can do in lots of ways. One of the most popular methods is to type your instructions using a programming language. A programming language takes your instructions and tries to understand them. If your instructions make sense, the programming language tells the chips and other parts of the computer what they need to do.

Programming languages save you time because you don’t have to think about all the complicated things the computer is doing while it works. You can use instructions that look a bit like English, and the programming language does the rest.

Although Scratch is a very simple programming language, it’s very unusual. Most languages don’t give you instruction blocks you can clip together. Instead, you write commands — special words that tell the computer what you want it to do. The list of commands you write is called code.

To make a program, you type code on the keyboard into an editor. An editor is a bit like a notepad application or a word processor, but it has special features to help you write code. Some editors can even run code for you so that you can check whether it works right away.

Find Python on the Pi

A version of Python with a matching editor is included in Raspbian. It appears on the desktop as IDLE, as shown in Figure 8-1.

warning The figures in this project use the older Pi desktop, so you can see what it looks like in case you buy a memory card with an older version of NOOBS. You can find the newer Pi desktop throughout the rest of this book. Python works the same way on both desktops.

To get started with Python, do the following:

  1. Power up your Pi, if isn’t already running.
  2. If you don’t have the desktop open, type startx and press Enter to launch it.
  3. Find the icon labeled IDLE.

    warning If you look very, very carefully, you’ll find an icon labeled IDLE 3. Ignore it. It launches a different kind of Python. If you try to use it, some of the code in this book won’t work. This will make both of us unhappy, so don’t click that icon!

  4. Double-click the icon.

    You should see a window labeled Python Shell, as shown in Figure 8-2.

    warning On the newer desktop, click the Menu button at the top right and choose Programming ⇒ Python 2. Ignore Python 3!

technicalstuff In computer-land, shells have nothing to do with the sea. You use a shell to tell the computer what to do. Here, you use the Python shell to tell Python what to do. The shell includes an editor for code, but you can also use it to send simple commands to Python. The shell runs them and shows you what Python does with them.

technicalstuff You’ve likely noticed that the date at the top of the window isn’t the current date. It’s the date when the people who made Python released it into the world for everyone to use. Some people get confused by this date, so it’s good to unconfuse them.

Set up Python

Before you try using Python, you can make the text in the editor bigger and easier to read. You can skip this step if you have awall-sized monitor and can see the text just fine. Otherwise, do the following:

  1. In the menu at the top of the Python Shell window, click Options.
  2. Click Configure IDLE, as shown in Figure 8-3.

    The Idle Preferences window appears.

  3. In the Font tab, click the Size box.
  4. Click a number in the drop-down list, as shown in Figure 8-4.

    The default size — the one that’s preselected for you — is 10. To make the text bigger, select a bigger number. The Python examples in this book use 14 to make them easy to read on the page. That size may be too big for you. Try setting the size to 12 first.

  5. Click Ok to set the new size.

    When you change the text size, the text gets bigger, and the window gets bigger, too.

warning If you set a really big text size you’ll get a window that may not fit on the screen. This doesn’t usually cause issues, but it can look kind of weird and disturbing. If the window is toooooo wiiiiide, you can’t see all the text in it, which is not what you want.

Unleash Python math power

Now you can unleash the full power of Python supercomputing. The line with the angle brackets is called a prompt. It’s like the Linux command prompt, except that it sends commands to Python instead of Linux.

Type the following at the prompt and then press Enter:

>>>1+1

Woo hoo! Python instantly solves this tough problem, as you can see in Figure 8-5.

Obviously, Python can do harder math. Try something like

>>>1/81.0*100

Don’t forget to press Enter. You’ll see that Python has no problem with more complicated sums.

tip Python is more accurate than a basic calculator. Try the same sum on a calculator, and you get a shorter and less precise answer. This small difference doesn’t matter for simple classroom math, but some college-level math problems need very accurate answers. A calculator isn’t good enough — but Python is.

Make mistakes

Figure 8-6 shows what happens when the shell can’t understand what you want — either because you made a mistake or because you tried to confuse it, like I did here. Although it’s totally not obvious, the weird message that appears means “I didn’t understand that last command. Try again.”

technicalstuff Python can show all kinds of error messages. When you’ve used Python for a while, you can see the messages are trying to give you useful hints. Until then, they’re hard to understand because they look kind of random. This problem occurs in most programming languages. When something goes wrong and you see error messages, they look like weird not-quite-English. They’re often not as clear and helpful as maybe they could be.

Remember Information

Programming languages spend a lot of time remembering information. In most languages, including Python, you remember things by making imaginary boxes to store the information. You have to give each box a different name so that you don’t get them mixed up.

Boxes hold one piece of information at a time. You can change what’s in a box, and you can open the lid to see what’s inside it.

As a simple start, store a number in a box. (You can also store words in boxes, but words need special code, so don’t try that yet.)

In computer-speak, boxes are called variables. This is a big, scary word, but it just means a box with something in it.

technicalstuff When you learn more about Python, you’ll see that you can put boxes inside other boxes to make collections. Often, it’s useful to do something to lots of boxes at the same time. It’s much easier to do this if you put them in a collection. Otherwise, you end up with boxes all over the floor and a giant mess.

Make a variable

To make a variable and put a number inside it, type the following and then press Enter:

my_number = 1

You can maybe guess what this does: It makes a box called my_number and puts 1 in it.

warning The line between the two words in the box name is called an underscore. It’s not the same as minus sign. If you type a minus sign by mistake, Python gets confused. On most keyboards, you can type an underscore by holding down the Shift key and pressing the key with the minus sign.

If you don’t make any mistakes, Python swallows this code, and nothing much seems to happen. Python shows a prompt on a new line and carries on waiting.

But if you type

print my_number

and press Enter again, Python looks through its box collection to find the box called my_number. Then it shows the value you told it to remember, as shown in Figure 8-7.

Variables are variable, so if you type

my_number = 2

press Enter and then check what’s in my_number now, you’ll see you’ve successfully put 2 in it, as shown in Figure 8-7.

tip The print command doesn’t print on paper — it prints on the screen. In the shell, you don’t have to type print to look inside a box. It’s included here to make the examples clearer. But if you’re in a hurry, you can leave it out and just type the variable name. This works only in the shell! In the editor, you have to use print when you want Python to show you what’s inside a variable.

Use variables

Why waste time putting numbers in boxes? Here’s a neat magic trick: You can tell Python to do math on numbers in boxes. Type the following (and don’t forget to press Enter at the end of every line):

my_other_number = 10

my_number*my_other_number

Python does its calculator thing on the numbers in the boxes.

This is HUGE! It means that when you have lots of variables and all kinds of information, you can combine everything in complicated ways.

For example, instead of adding up a list of numbers by hand, you can give them to Python, and it can do the sum for you. If any of the numbers change, you can change the value in one box and tell Python to redo the sum.

You don’t have to type all the numbers again. Awesome!

Make recipes

You have gained your first computer superpowers. You can make boxes, put values in them, and do math on them. One final god-like trick is to put the value of math you do into a new box, like this:

my_big_number = my_number * my_other_number

technicalstuff In computer-speak, use the * symbol when you want to multiply numbers. It’s usually above the number 9 on the number pad on your keyboard, or on Shift + 8. Don’t use x or X because Python will think you’re trying to do something with text or letters or something, and it won’t work.

This one line of code is beyond awesome. You’ve made a recipe for working with information. You don’t need to know what’s in the boxes. The code just works as long as the variables hold numbers. It doesn’t care what the numbers are. It works for all of them.

warning The catch is that you can’t multiply words, collections, photos, or music!

Writing a computer program often means making a list of recipes. For example, instead of doing math on specific numbers, you can make a list of math recipes. Then you can use them over and over whenever you need some math to happen.

This is why computers are so useful. You can build recipes that do useful things to almost any kind of information — not just numbers, but words, videos, music tracks, web pages, and pictures of cats being cute and dogs falling off skateboards.

technicalstuff In computer-speak, recipes are called algorithms — maybe because calling them recipes doesn’t sound serious and grown-up enough. It’s always better to use a difficult word when you want to look grown-up.

Use the Shell and the Editor

Wasn’t IDLE supposed to be a code editor? How do you type and edit code in the shell? What does the shell do anyway?

In the shell window, you type code line by line directly into Python. When you press Enter, the shell checks whether your code makes sense. If it does, it sends it to Python. If Python returns a result — like the answer to a basic math problem — it shows it in the window.

In outline, the shell recipe looks like this:

  1. Show the prompt and wait for the user to type a command and press Enter.
  2. Read in the command.
  3. Check if it makes sense.
  4. If there’s a problem, complain to the user and go to Step 7; if everything is fine, send the command to Python and continue to Step 5.
  5. Wait for Python to run the command and return a result.
  6. If there’s a result, show it in the shell window.
  7. Show the prompt and wait again.

You don’t need to remember this list. The point here is that the shell is a computer program. The creators of Python had to sketch out a list like this so they knew what the shell had to do. Then they wrote code for each step to make it work.

Python is really, really complicated on the inside. But when you make your own programs, it’s a good idea to sketch out the steps for your code before you start.

A sketch of steps is sometimes called a specification. It’s like a recipe for the entire program, but it doesn’t include the code thatmakes each step work. A good specification outlines everything a program does. It even includes all the things that can go wrong, so the program is smart enough to handle mistakes made by human users.

A specification is a bit like a map you can use to find your way around the code. Each block of code does a small and simple thing. When you put all the blocks together, they do something big, complicated, and clever — like running Python, making a big website work, managing all the apps in your phone, or making sure your microwave makes popcorn without bursting into flames and burning down the house.

Open the Editor window

What if you want to run a series of commands without having to type them one by one? You can also do this in IDLE, but you have to open the editor window first.

To open it, choose File ⇒ New Window. Figure 8-8 shows the result. When you open a new editor window, it’s labeled Untitled. It’s completely blank, with no prompt, and the menu options are different.

Add code

To write code, type it into the window. As usual, press Enter at the end of each line. The editor doesn’t try to run your code. It just moves the text cursor to the next line.

To keep things simple, type code based on the commands in the rest of this project. Make a couple of variables, put numbers in them, and do some simple math on them. Include a print command to show the result.

Figure 8-9 shows some possible code, which I also list here so that you don’t have to squint at the page:

my_number = 1234

my_other_number = 5678

my_product = my_number * my_other_number

print my_product

tip When you type, the editor highlights words that Python recognizes in red. Python doesn’t recognize your variables names because you invented them. It does recognize print because it’s a Python command.

Run code

How do you send the code to Python to run it? Click Run  ⇒  Run Module F5 or press F5 on your keyboard.

And, nope, you still can’t run it. That’s because you have to save the code first. If you haven’t saved it, Python nags you with an alert box. Click OK in the alert box to open a save dialog box, shown in Figure 8-10.

The file selector points to your home directory in Linux. If you logged in as the usual Pi user, this is /home/pi.

Type a file name and click the Save button. Python files need a .py extension. Remember to include it. For example, you might name the file my_first_code.py.

warning If you’re lazy you could name it a.py, but then you’ll come back to your home directory a few months from now and wonder what all the Python projects you named a.py, b.py, c.py … do.

Unfortunately, you can’t create directories in the file selector. This is a bad thing, but it’s how it is. If you want to keep all your Python projects in a directory — a good idea, but not totally essential — click Cancel in the file selector and open the desktopFile Manager. Create a new directory called python_code in /home/pi. Include the underscore and don’t use a space because it makes it easier to use the directory from the Linux command line.

Click the Save button. Python switches to the shell window and displays a big RESTART message. If your code doesn’t have any mistakes, you’ll see a number like the one Python works out and displays the answer. The number you get depends on the numbers in your code and the math you did with them.

Check code

If you made a mistake, click the editor window and look at your code again. Did you leave out an underscore or use a minus sign instead? Did you mistype the variable names so that they don’t match where they should? Did you use an X instead a *? Did you add any extra letters or characters? Did you put all your code on one line?

Computers are super-picky. Python doesn’t care how you spell variable names. yo_sup_dawg, bannnnnnnnnana and ftryurgh will all work. But if you don’t use exactly the same names throughout your code, with exactly the same spelling and underscores, Python gets very confused.

Near enough isn’t good enough. Exactly means exactly the same. No exceptions. (Did I mention that already?)

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

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