PROJECT 1

Getting Started with Python

In this project, you’re introduced to Python: where it’s used and what it’s used for. I explain the two current versions of Python. This book is focused on Python 2.7 and I explain why. With my help during this chapter, you install a copy of Python 2.7 (if you don’t already have it installed) and fire it up. I also tell you how to stop once you’ve started.

image

This project also shows you how to get Python’s documentation, both built in to Python and online. I give you ways to search online for answers to your Python problems, just in case you’ve never searched the Internet before. You also read about the Python community, which is one place you can go for help or new ideas. All that, but no actual programming? No worries. Actual programming starts in Project 2.

TL;DR: If you’ve already installed Python, and you can start and stop it, then skip to Project 2.

Python and Why It’s Wonderful

Python is a programming language written by a person called Guido van Rossum in the 1990s. Programming languages allow you to control what a computer does and the way it does it.

Some of the things that make Python totes awesome (also known as “really helpful and lots of fun”) are:

  • Python code is easy to read and understand. In fact, I think Python’s code is sublime and beautiful. (Hey, that’s just my opinion.) Its beauty means you don’t even notice the way Python makes complex things simple. This makes Python easy to learn, which makes it perfect for kids.
  • Python is productive. It makes tough tasks simple. Almost any programming task is easier with Python than it is with other programming languages. Computer types call this RAD (for Rapid Application Development).
  • Python is dangerous. It has a lot of power. But with great power comes great responsibility. (Remember Spider-Man?) And you’ll have to use your powers for good, not evil. (If you want to use them for evil, you have to stop reading now.)
  • Python is a scripting language. The programs are fed into Python’s interpreter, which runs them directly, so there’s no compiling (which is the case for some other languages). It is faster and easier to get feedback on your Python code (finding errors, for example). Python means you complete and execute (run) your programs faster and that makes programming fun!
  • Python is cross platform. Almost anyone can use it, no matter what computer operating system they have. You can run pretty much any Python program on Windows, Mac, and Linux personal computers and from large servers through to tiny computers like the Raspberry Pi. (A Pi-specific project is waiting at dummies.com/go/pythonforkids for you.) You can even run Python programs on Android and iOS tablets. I even used my Android tablet to code some of the early projects in this book.
  • Python uses dynamic typing for its variables. This may not mean much to you if you’ve never done programming before. Dynamically typed variables make programming easier because they let you just start using a variable, rather than first explaining to the computer what the variable is supposed to be.
  • Python gets lots of help from third-party modules. This means that a lot of other people (third parties) have written libraries. A library is a bunch of code for doing something specific. This makes your work easier because you don’t have to start from scratch every time you write a new program; sometimes you can use the libraries already written. The Minecraft project online uses a third-party library to change a Minecraft game on a Raspberry Pi.
  • Python is free software. This means that the license terms for Python respect your freedom. I think this is pretty important. You can download and run Python without paying any money, and any program that you write with it is yours to use and share any way you want. It also means that the Python source code (the human-readable form of what the computer runs) is available so, when you’re feeling brave enough, you can look at how the Python developers wrote their code. (It’s written in a different programming language, though, d’oh!)

Who’s Using Python

Python is used just about everywhere.

  • In space: The International Space Station’s Robonaut 2 robot uses Python for its central command system. Python is planned for use in a European mission to Mars in 2020 to collect soil samples.
  • In particle physics laboratories: Python helps understand the data analysis from some atom smashing experiments at the CERN Large Hadron Collider.
  • In astronomy: The MeerKat Radio telescope array (the largest radio telescope in the Southern Hemisphere) uses Python for its control and monitoring systems.
  • In movie studios: Industrial Light and Magic (Star Wars geniuses) uses Python to automate its movie production processes. Side Effects Software’s computer-generated imagery program Houdini uses Python for its programming interface and to script the engine.
  • In games: Activision uses Python for building games, testing, and analyzing stuff. They even use Python to find people cheating by boosting each other.
  • In the music industry: Spotify music streaming service uses Python to send you music.
  • In the video industry: Netflix uses Python to make sure movies play (stream) without stopping. Python is used a lot for YouTube.
  • In Internet search: Google used Python all over in its early development phase.
  • In medicine: The Nodality company uses Python to handle information that they use to search for a cure to cancer.
  • In your OS (admin-ing your datas): Operating systems like Linux and Mac OSX use Python for some of their administrative functions.
  • In your doorbell: Rupa Dachere and Akkana Peck say that you can automate your home with Python, hooking up sensors to your house. With it you can, for example, open and close the curtains or automatically turn on lights when you come in the room.

I could go on. The point is that Python will apply to whatever you’re interested in, no matter what it is.

Making Things with Python

You do these things while you work through this book:

  • Make a math trainer for practicing your times tables.
  • Make a simple encryption (a secret code) program.
  • Use Python on a Raspberry Pi to work with and modify your Minecraft world. (See www.dummies.com/go/pythonforkids for that project.)

When you’ve honed your mad skills and are ready to move on, there’ll be other things you can do:

  • Using Tkinter (or other widget sets), you can write user applications that use graphics rather than just text to interact with the user.
  • You can extend other programs like Blender (a 3D modeling program), GIMP (a 2D photo-retouching program), and LibreOffice (office programs), among many others by writing custom scripts. I had to fix some 3D models I was making in Blender. It would’ve taken forever to do by hand, so I wrote a Python script to do it quickly.
  • You can write games with graphics using Tkinter or the Pygame or Kivy libraries. The games in this book are text only.
  • You can use the matplotlib library to draw complex graphs for your math or science courses.
  • Using the openCV library, you can experiment with computer vision. People who are into robotics use it to help their robots see and grab things and to avoid obstacles when moving.

Whatever you want it to do, there’s a good chance someone has already written code to do it or to help you do it yourself.

Understanding This Book’s Pedagogical Approach

That title is just to impress your parents. (I hope they’re not reading this part. But look: If they don’t see that title, tell them that this book has a pedagogical approach — ped-uh-goj-i-cul. It means education or teaching.)

The point of this book is to give you a chunk of information about the programming concepts that you need to program in Python. The book is for you — a kid who can learn Python.

I am thorough

Thorough, yes. Will I include everything? No way. Many aspects of Python have lots of options. If I took you through all the possibilities of each option, you’d fall asleep (or throw this book out the window). If you do either of those things, then you won’t be learning.

As you read, remember that I’ve tried to introduce you to enough information so you can be a Python programmer, but not so much that you’d need superhuman powers to get through it. Expand on your own using the documentation and help.

You start pretty slowly with core (main) principles. If you think things aren’t going fast enough, skip ahead! The examples are generally self contained. This means that you end up with many smaller projects rather than a few larger projects. I did that on purpose so you can do the projects in any order you like. You’ve got enough people telling you what to do. You can go where you want to in this book.

The earlier projects use plain English, rather than technical words. As you go through the book, you’ll see more jargon. You’ll also get less hand holding. You’ll have to work harder the further you get through the book.

I walk you through programming

The projects try to show you realistic programming without boring you to tears. When you write your own code to solve your own problems, you’ll need methods and approaches (tools) that get the job done. I teach you these tools by walking you through each project, step by step. Try every step — don’t skip any.

If you want to run the working program, skip to the end of the project and cut and paste. If you want to learn Python, then consider each project a journey, not a destination. Work through the projects with me and type them in yourself.

I am practical

Hopefully, you can use these projects for something in your everyday life. Maybe they’ll help with your homework or let you store private notes. I start small and dream big. Please dream big with me while you’re getting the concepts in the first projects.

Install Python on Mac OSX

To find and start Python on Mac OSX computers, follow these steps:

  1. Press Cmd+spacebar to open Spotlight.
  2. Type the word terminal.

    Or, from the Finder, select Finder ⇒ Go ⇒ Utilities ⇒ Terminal.

    The Terminal window opens.

  3. In the terminal, type python.

    The Python interpreter that’s built in to Mac OSX opens.

Install Python on Windows

Unfortunately, Python doesn’t come on Windows. If you’re running Windows, then you need to download and install Python by following the instructions here. Installing Python on Windows isn’t difficult. If you can download a file from a website, you have the skills to install Python.

Fortunately, the Python Foundation (the peeps who guide the development of Python) makes installable files available from its website.

When I did the installation, I found that Firefox and Internet Explorer responded differently to the Python download website, so the instructions are based on which of these browsers to use. If you use a whole other browser altogether, try the Internet Explorer instructions.

With Firefox

To install Python on a Windows machine with Firefox, follow these steps:

  1. Visit www.python.org/downloads.
  2. Click the button that says Download Python 2.7.9.

    Or, if it’s there, click a more recent version number that starts with 2.7.

    Clicking this button automatically downloads and saves an msi file for you. If not, try the instructions for Internet Explorer. See Figure 1-1.

  3. When the download’s complete, click the icon for Firefox’s download tool.
  4. Click the file called python-2.7.9.msi (or the more recent version, if you downloaded one).

    Python 2.7.9 installs on your computer.

image

Figure 1-1: Download Python with Firefox.

With Internet Explorer

To install Python on a Windows machine with Internet Explorer, follow these steps:

  1. Visit www.python.org/downloads.
  2. From the menu bar, select Downloads ⇒ Windows.

    You can see the menu options in Figure 1-2.

  3. Scroll down to the heading Python 2.7.9-2014-12-10.

    Or scroll to a more recent version, which starts with Python 2.7, if one is available.

  4. Under this heading, click the link titled Download Windows x86 MSI Installer.

    warning See Figure 1-3. This is a link for a 32-bit installation, which makes things work better with third-party libraries. Use the 32-bit installer even if you have a 64-bit machine and even if you have no idea what this paragraph is talking about.

  5. If you’re asked to choose whether to run or save the file, choose Run.

    This downloads python2.7.9.msi and starts running the installer.

  6. If you get a security warning when the installer begins (or at random times during the installation), choose Run.
  7. Accept the default installation options that the installer provides.
image

Figure 1-2: Download Python with Internet Explorer.

image

Figure 1-3: Python x86 MSI Installer.

Install Python for Linux

If you’re running Linux, confirm that you have version 2.7.9 of Python installed, rather than version 3. This shouldn’t be a problem because Python 2.7 is installed by default in recent versions of OpenSuSE, Ubuntu, and Red Hat Fedora.

In the nutty odd case when someone has Python 3 but not Python 2.7, read your distribution’s documentation for how to use the package manager and get Python 2.7 and IDLE.

Pin Python to Your Start Menu

After you’ve downloaded Python, it’s a good idea to pin it to your Start menu. That way you can find it more easily for the rest of this book.

Type Python in the Start menu’s search bar, or click All Programs. In the folder Python 2.7, you should find the following entries (see Figure 1-4):

  • IDLE (Python GUI)
  • Module Docs
  • Python (command line)
  • Python Manuals
  • Uninstall Python
image

Figure 1-4: Python entries in Start menu.

Of these, you’ll use:

  • IDLE (Python GUI)
  • Python (command line)

To make IDLE and the command line easier to find, pin them to your Start menu:

  1. Open your Start menu.
  2. Choose All Programs ⇒ Python 2.7.
  3. Right-click IDLE (Python GUI). See Figure 1-5.
  4. Select Pin to Start Menu.
  5. Right-click Python (command line).
  6. Select Pin to Start Menu.

    You should see the entries at the top of your Start menu. If you prefer, you can pin them to your taskbar.

image

Figure 1-5: Right-click to pin Python to your Start menu.

Start the Python Interpreter

You can’t use this book unless you can start Python. Click Python (command line) that you pinned to your Start menu.

tip If you haven’t pinned it yet, do it. No, seriously. You can also search for Python in the search bar and click Python (command line) in the Programs section of the results.

You get a window that looks like Figure 1-6.

image

Figure 1-6: The Python command line suggests you type help if you want help.

Use Python’s Built-In Documentation

Python comes with its own help. In fact, in Figure 1-6 it even tells you about it in the welcome message. If you type help and press Enter, you get more help options. Type help() (including the parentheses) to get interactive help like what you see in Figure 1-7.

image

Figure 1-7: Python’s interactive help is ready for you to type.

tip Once you’re inside the help service, you can get information on any topic. Just type the topic. The help service can’t handle complex queries (like the ones you use to search the Internet), so keep it simple. For example, instead of typing how do I get a range of numbers, type range (and read what it has to say). To quit interactive help, type quit.

You can write help text for your own programs. You do it in Project 5.

Put the Kibosh on the Python Interpreter

You can’t use this book unless you can start Python, but you’ll want to stop Python after you’ve started it. If you can’t wait to start programming, skip ahead to Project 2.

You can put the kibosh on Python from the command line by doing one of the following:

  • Type exit(), including the parentheses. Press Enter. (This works on any platform; Enter = Return if you’re on a Mac.)
  • Click the close icon for the window that Python’s running in. (This works on any platform.)
  • On Windows, type Ctrl+Z and then press Enter.
  • On Linux and Mac, type Ctrl-D.

tip If you’re on a Mac, make sure you’re using the Ctrl key, not the command key. Also, anytime I mention the Enter key, this means the Return key for you.

Find Python Documentation Online

As I mention, this book doesn’t cover every single possible potential thing you could do with Python. I just can’t do that in a single book.

Instead, this book exposes you to programming in Python. Sort of like the measles. Use this book as a starting point. If you want more information, you should check out

  • Python’s online documentation
  • Python’s introspection features
  • Professor Internet
  • Source code (not so much)

Python’s online documentation

The Python documentation pages are available at https://docs.python.org/2.7/. The most helpful sections are listed here:

tip In the left sidebar of the documentation page is a quick search field; you can see it in Figure 1-8. Type your question there and Python will search the documentation for you. It works better if you know the Python keyword, module, or error that you’re interested in.

image

Figure 1-8: Python’s online documentation can help.

The documentation shows the feature you looked for and a code template for how to use the feature. (See this book’s Introduction for how to read code templates.) These docs have a lot of information, but they assume you know how programmers write documentation. This often makes them hard to understand.

Reading the Python documentation is a skill that you have to master if you want to become a Python master. At the moment, though, don’t worry that it seems like it’s written in a foreign language. Just work through it slowly. As you read more of it, you’ll be able to get more information from it. Soon, docs you couldn’t understand at all will become mind-numbingly boring. Then you’ll know you’re making progress!

Python’s introspection features

The second form of help is Python’s introspection features. Introspection means that the program can tell you about itself. Introspection has a lot of different parts. You’ve already met one of them — the help feature. To understand the others you need to know more about Python, so I introduce the rest as you work your way through the book.

Professor Internet

What I like to call “Professor Internet” is the third form of help. When you search the Internet, make sure you include Python as one of your search terms, followed by the thing you’re wondering about. If you know that it’s part of or related to something else, then include that other thing as a search term as well. For example, don’t search for print, because that’s too broad. Search instead for python print. (Capitalization won’t matter.) Another example is if you were interested in the Button widget of the Tkinter toolset (which you meet at dummies.com/go/pythonforkids) you’d search for python button tkinter.

remember You use a different search strategy online from what you need for the interactive help.

If ads are in your results, skip them.

Source code

Source code is the final form of help. Keep in mind that Python is an interpreted language. This means that what you read is what the computer executes. As a result, if you want to know how some third-party module does something (the Python core isn’t written in Python, so that won’t help), you can literally look at it and see exactly how it did it. You won’t understand it at first, but no matter. Dive in. It starts making sense after a while.

Join the Broader Python Community

Check out the Python community that’s out there. Look for Internet forums related to Python. The Stackoverflow website (http://stackoverflow.com/questions/tagged/python) is helpful when I’m figuring out problems.

Often, an Internet search will turn up questions that someone else has already asked. If you know the answer to a question, answer it. If you’re correct, and thorough, you’ll get a good reputation.

warning Don’t guess at an answer. Only post if you’re sure. Also, don’t give your personal information to anyone online. Stick to the topic of programming.

PEPs

Python changes, or evolves, when you use proposal documents called Python Enhancement Proposals (known as PEPs). Each PEP proposes some change to Python; the change is either used or ignored. They may provide you some history about how one feature or another was added to Python.

You can ignore most PEPs, but do check out the following two when you’re ready to move on from the projects in this book:

  • PEP 8, Style Guide for Python Code has rules about how to format your Python code. For example, it suggests the amount of indent for code blocks (see Project 2). It also has rules (called conventions) for naming. I did my best to follow PEP 8 rules in this book, but sometimes the lines are longer than they recommend.
  • PEP 257, Docstring Conventions sets different conventions relating to docstrings. Docstrings explain, in normal language, what a program (or part of one) is doing. You meet docstrings in Project 5.

tip You don’t have to follow (comply with) with PEPs, but try to. It makes it easier for other people to read your code. Heck, it makes it easier for you to read your code. My earlier Python code isn’t PEP 8 compliant, and going back to it is a real pain. Simple things like capital letters in a name make a difference.

Planet Python and PyCon

Planet Python (http://planetpython.org) puts together lots of blogs that are Python related. Many of the posts may be hard to understand as a beginner, but like everything else, stick with it — they’ll become clear. A lot of top-notch Python programmers have their blogs on Planet Python. You can learn heaps from keeping an eye on them. I have.

Python programmers regularly get together at conferences around the world. These conferences (confs) are called PyCon, and their location is added to the name. For example, the one in Australia is called PyCon-AU. See www.pycon.org for a list of locations.

I’m not suggesting you hop a plane to Australia to attend PyCon-AU (or even attend one that’s close to you). However, I am suggesting you hop online and check out the videos from these confs. The videos from various PyCons appear over time at http://pyvideo.org. Go there, browse, find something that looks interesting, and watch. It’s a great way to get a quick introduction (or an in-depth look) at something new.

tip If you can find them, look at the slide decks for PyCon talks. The slide decks are a little harder to find, but easier to download and review. Look at them first. I often just go off the slide decks, but you might decide to download the video too.

Handle Problems

There are two main kinds of errors:

  • A syntax error basically means you made a punctuation mistake. These are the most common errors. Get used to reading what you’ve typed very closely and comparing it carefully to what you should have typed.

    tip If you have trouble getting one of the code examples to run properly, the first thing to do is make sure that you’ve retyped the code exactly as it’s written.

  • Logic errors occur where you’ve misunderstood what you’re trying to do or what you’ve asked Python to do. These errors can be difficult to spot and more difficult to track down. Compare the output that you actually get to the output you ought to get. This means that you need some way of working out the output that you ought to be receiving. Project 6 shows a logic error and the steps to identify and resolve one.

When Python runs into an error, it tries to give you a clue about what went wrong and where. Try to figure out Python’s message. It will usually give you a good place to start.

Sometimes you get an error because you’ve assumed something that is incorrect. If you can’t see what’s wrong, think about the assumptions you’ve made. If you’re not making any progress, do something else and reset your brain. Go drink some water, feed Fluffy, or stand up and walk around. Do something that gets your mind on something else, but doesn’t steal your brain. (Hopping onto Instagram isn’t a good idea, for example.) When you’ve finished that, come back to your Python problem. Fresh eyes and a fresh mind will help you see the problem differently and hopefully lead to a solution.

If all else fails, bring Fluffy (or your dog, or goldfish, or your pet rock) nearby when you’re coding. If you come to a problem you can’t solve, stop what you’re doing and explain the problem to your pet or object.

tip Explaining things out loud is an old debugging (error fixing) technique. It works because, in order to explain the problem to someone else, you have to first understand it yourself.

You need to express your problem using words because this causes a different part of your brain to kick in and you think differently about the problem. If you’re like me and you’re not the talking type, keep a programming journal. The concept is still the same — write out an explanation of the problem in your journal and why you can’t crack it. I promise you this will help you solve many difficult problems.

Learn How to Learn

Reading books isn’t enough. You have to do. Be the book, feel the book, become one with …. (Scratch that last bit. I was channeling a movie there for a second.)

Do

Seriously. You need to actually do things if you want to learn. No one ever learned anything by simply reading. It’s true of Python, and it’s true of anything else you want to learn.

Do the code as you read the book. Don’t just cut and paste. Type the whole thing in again yourself, at least for the early projects. That way, you read the code that’s been written and somewhat understand why it’s been written that way. Copying and pasting won’t get you close to the code. Go on. Snuggle up. Freestyle it if you want to add your own changes. You learn faster if you add your own stuff. Own the code!

Make mistakes

If you do, you’re gonna whoops. If you’re freestyling, don’t worry about breaking your code or getting things wrong. (Use Save As to make backups.)

Everyone who writes code gets it wrong the first time. Their logic is wrong; they misspell something. Whatever.

tip Making mistakes is as important as doing.

This is totally normal. In fact, writing programs is a process, and it has wrong turns and setbacks. Professional programmers make mistakes every day. That doesn’t bother them because they code in small pieces that they can handle, and they test what they do.

Think

When you get something wrong, or your code doesn’t work like you expected, take the time to understand why. If you think long and hard enough, you’ll work it out.

Getting things wrong isn’t enough to teach you. It’s part of a path to thinking and understanding. That’s where the learning comes from. See how it all builds on itself? Sort of like Python.

Ganbatte Ne!

The Japanese have a most excellent word — ganbatte. It means a whole heap of different things like cheer up, good luck, do your best, be strong, keep at it, keep your chin up, be courageous, don’t give up, and you can do it. When you start learning a programming language, you have big dreams but small skills. It can feel even tougher because the examples of computer programs you see were made by teams of people working for months on end. Plus, a lot of what makes programs seem special these days is graphic artists, and that’s a whole new ballgame!

Hang in there! Your effort will be rewarded.

Summary

In this project you:

  • Saw where and how you can use Python
  • Discovered the two versions of Python and why this book uses Python 2.7
  • Installed Python on your computer, started it, and stopped it
  • Met Python’s built-in help and its online documentation
  • Were briefly introduced to the Python community
..................Content has been hidden....................

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