Python Basics: Get to Know Your Environment - Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (2015)

Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (2015)

Chapter 1. Python Basics: Get to Know Your Environment

Just about anything could have a computer in it — a phone, a car, a watch, a video game console, an exercise machine, a medical device, industrial equipment, a greeting card, or a robot. Computer programming, or coding, is how we tell a computer to perform a task, and understanding how to code puts the power of computers at your fingertips.

Computer programs — also called applications, or apps — tell computers what to do. A web app can tell the computer how to keep track of your favorite music; a game app can tell the computer how to display an epic battlefield with realistic graphics; a simple app can tell the computer to draw a beautiful spiral like the hexagon in Figure 1-1.

A colorful spiral graphic

Figure 1-1. A colorful spiral graphic

Some apps are composed of thousands of lines of code, while others may be just a few lines long, like the program NiceHexSpiral.py in Figure 1-2.

NiceHexSpiral.py, a short Python program that draws the spiral in

Figure 1-2. NiceHexSpiral.py, a short Python program that draws the spiral in Figure 1-1

This short program draws the colorful spiral shown in Figure 1-1. I wanted a pretty picture to use as an example in this book, so I decided to solve that problem using a computer program. First I sketched out an idea, and then I started coding.

In this chapter, we’ll download, install, and learn to use the programs that will help us write code to build any kind of app you can imagine.

Getting Started with Python

To begin coding, we have to speak the computer’s language. Computers need step-by-step instructions, and they can only understand certain languages. Just like a person from Russia might not be able to understand English, computers only understand languages made for them. Computer code is written in programming languages like Python, C++, Ruby, or JavaScript. These languages allow us to “talk” to our computer and give it commands. Think about when you teach a dog to do tricks — when you give the “sit” command, he sits; when you say “speak,” he barks. The dog understands those simple commands, but not much else you say.

image with no caption

Likewise, computers have their own limitations, but they can do whatever you tell them to do in their language. The language we’ll use in this book is Python, a simple, powerful programming language. Python is taught in introductory computer science courses in high school and college, and it’s used to run some of the most powerful apps in the world, including Gmail, Google Maps, and YouTube.

To get you started using Python on your computer, we’ll go through these three steps together:

1. Download Python.

2. Install Python on your computer.

3. Test Python with a simple program or two.

image with no caption

1. Download Python

Python is free and easy to get from the Python website, shown in Figure 1-3.

The Python website makes it easy to download Python.

Figure 1-3. The Python website makes it easy to download Python.

In your web browser, go to https://www.python.org/. Hover your mouse over the Downloads menu button near the top and click the button that begins with Python 3.

2. Install Python

Find the file you just downloaded (it’s probably in your Downloads folder) and double-click it to run and install Python and the IDLE editor. IDLE is the program we’ll use to type and run our Python programs. For detailed installation instructions, see Appendix A.

3. Test Python with a Program

In your Start menu or Applications folder, find the IDLE program and run it. You’ll see a text-based command window like the one shown in Figure 1-4. This is called the Python shell. A shell is a window or screen that lets the user enter commands or lines of code.

The IDLE Python shell — our command center for learning Python

Figure 1-4. The IDLE Python shell — our command center for learning Python

The >>> is called a prompt, and it means that the computer is ready to accept your first command. The computer is asking you to tell it what to do. Type

print("Hello, world!")

and press ENTER or RETURN on your keyboard. You should see the Python shell respond by printing the text in quotes that you entered inside the parentheses: Hello, world!. That’s it — you’ve written your first program!

Writing Programs in Python

You’ll usually want to write programs that are longer than a single line, so Python comes with an editor for writing longer programs. In IDLE, go to the File menu and select FileNew Window or FileNew File. A blank screen will pop up, with Untitled at the top.

Let’s write a slightly longer program in Python. In the new, blank window, type the following three lines of code:

# YourName.py

name = input("What is your name?\n")

print("Hi, ", name)

The first line is called a comment. Comments, which begin with a hash mark (#), are programming notes or reminders that the computer ignores. In this example, the comment is just a note to remind us of the program’s name. The second line asks the user to input their name and remembers it as name. The third line prints "Hi, " followed by the user’s name. Notice that there’s a comma (,) separating the quoted text "Hi, " from the name.

Running Programs in Python

Go to the Run option on the menu above your program and select RunRun Module. This will run, or carry out, the instructions in your program. It will first ask you to save the program. Let’s call our file YourName.py. This tells your computer to save the program as a file calledYourName.py, and the .py part means this is a Python program.

image with no caption

When you save the file and run it, you’ll see your Python shell window start the program by showing the question What is your name?. Type your name on the next line and press ENTER. The program will print Hi, followed by the name you typed. Since this is all that you asked your program to do, the program will end, and you’ll see the >>> prompt again, as shown in Figure 1-5.

The computer knows my name!

Figure 1-5. The computer knows my name!

For younger learners, like my three-year-old son, it’s fun to explain that the program is asking them to type their name. Max knows the letters in his name, so he types m-a-x on the keyboard, and he loves it when I tell him the program said Hi, max back to him. Ask your young learner if she’d like the program to say something different. Max said “Hello,” so I edited the earlier program on the third line to say Hello, instead of Hi,.

Then I changed the third line to read:

print("Hello, ", name, name, name, name, name)

Max loved it when the program replied to him with Hello, max max max max max. Try experimenting with the second and third lines of the program to have the computer ask different questions and print different answers.

What You Learned

Learning to code is like learning to solve puzzles, riddles, or brainteasers. You start with a problem, apply what you know, and learn new things along the way. By the time you finish, you’ve exercised your mind, and you’ve answered a question. Hopefully, you’ve also had fun.

In this chapter, we solved our first major problem: we installed the Python programming language on our computers so that we could start coding. It was as easy as downloading a file, installing it, and running it.

In the chapters that follow, you’ll learn how to solve problems using code. You’ll start with simple visual puzzles, like drawing shapes on the computer screen (or a tablet or phone), and then find out how to create simple games like Guess a Number, Rock-Paper-Scissors, and Pong.

From the foundation you’ll build in these first programs, you can go on to code games, mobile apps, web apps, and more.

At this point, you should . . .

§ Have a fully functional Python programming environment and text editor.

§ Be able to enter programming commands directly into the Python shell.

§ Be able to write, save, run, and modify short programs in IDLE.

§ Be ready to try more advanced, fun programs in Chapter 2.

PROGRAMMING CHALLENGES

At the end of each chapter, you can practice what you’ve learned — and make even cooler programs! — by trying a couple of challenges. (If you get stuck, go to http://www.nostarch.com/teachkids/ for sample answers.)

#1: MAD LIBS

The simple YourName.py app has all the necessary components for us to build a much more interesting program, like the old-fashioned Mad Libs word games (go to http://www.madlibs.com/ if you’ve never tried one before).

Let’s modify the program YourName.py and save it as MadLib.py. Instead of asking for the user’s name, we’ll ask for an adjective, a noun, and a past-tense verb and store them in three different variables, just as we did for name in the original program. Then, we’ll print out a sentence like “The adjective noun verb over the lazy brown dog.” Here’s what the code should look like after these changes.

MadLib.py

adjective = input("Please enter an adjective: ")

noun = input("Please enter a noun: ")

verb = input("Please enter a verb ending in -ed: ")

print("Your MadLib:")

print("The", adjective, noun, verb, "over the lazy brown dog.")

You can enter any adjective, noun, and verb you wish. Here’s what you should see when you save and run MadLib.py (I’ve entered smart, teacher, and sneezed):

>>>

Please enter an adjective: smart

Please enter a noun: teacher

Please enter a verb ending in -ed: sneezed

Your MadLib:

The smart teacher sneezed over the lazy brown dog.

>>>

#2: MORE MAD LIBS!

Let’s make our Mad Lib game a little more interesting. Start a new version of MadLib.py by saving it as MadLib2.py. Add another input line that asks for a type of animal. Then, change the print statement by removing the word dog and adding the new animal variable after the end of the quoted sentence (add a comma before your new variable inside the print statement). You can change the sentence more, if you’d like. You could wind up with The funny chalkboard burped over the lazy brown gecko — or something even funnier!