Python/Getting Started/Step 2

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Now what?

Do not continue reading this tutorial until you have done the following:

  1. Installed Python on your computer and dinked around with it.
  2. Found a project written in Python that you'd like to contribute to and downloaded their code.
  3. Installed a proper Text Editor and begun learning the ropes.

If you haven't done those things, you're wasting everyone's time, so go do it and come back when you are ready.

OK, I did it.

Good. Now let's learn Python and how to program.

Your first task is to *read* the code you downloaded. That's right, find the Python files (they end in .py) and open them up in your text editor and start poking around.

This should look something like gobbledy-gook. I know, I know, you feel lost and like maybe you've taken on a project way to big to handle. Never fear, trust your teacher, we're going to get through this and you're going to learn how to program.

Look carefully at a single line in the program. It doesn't matter what it is. If you have syntax highlighting turned on (go turn it on) you should see that different kinds of lines have different colors. Let's cover the most obvious lines you'll see.

Comments

Comments are pieces of code that the computer ignores. They start with '#' and go to the end of the line. Here's an example.

a += 5  # Move 5 spaces to the right

That bit of code on the right, after the '#' is there for you, the reader. The programmer was kind enough to leave it behind so that you can better understand what is going on.

Now, comments are generally short and to the point, more like mile markers than roadmaps. If you know where you are, roughly, and what you are looking for, roughly, then they will help you get oriented. If you are lost, they are almost useless.

At this point, I recommend opening up whatever documentation came with the project. Just start reading it. It won't make sense --- the authors are writing in a different language, for all intents and purposes, talking about ideas that you've never had in your head yet. Don't worry, you'll get them eventually. We're all human, after all, and programming languages are written for us.

The code

For the most part, Python processes the code from the top to the bottom. The code at the top runs first, then the next line, then the next line. Each line of code does something (usually). There are a wide variety of instructions that you can give Python. You may see some symbols you recognize from math class: +, -. There are others that are new: * (multiply), / (divide).

Assignments

You might see equals signs '=' floating around. When there is a single equal sign, this is an assignment statement. It tells Python, "I'd like to set this variable to this value." If there are two equals together '==' then this is the equality operator. (We'll cover that later.) If there is a symbol right in front of the equals like '*=' or '+=' then it's also something different. Again, patience. We'll cover those later.

For now, let's find statements that say something like:

filters = 7

The assignment statement has three parts:

  • the bits on the left
  • the assignment operator '='
  • the bits on the right.

It's really that easy.

The bits on the left are the names of the variables the code is assigning values to. The bits on the right are the things being assigned.

What's a variable? A variable is like a box. Or rather, it's like an envelope. In Python, there is only one kind of variable. (In other languages, there are sometimes more than one.) In Python, all variables hold a bit of memory that is the address of the actual data that the variable is referring to.

This sounds complicated, but it's really not. Let me break it down for you.

First, a real world example. Let's take your name. My name is Jonathan. When you say "Jonathan", what do you mean? Why, you are *referring* to me. The name itself "Jonathan" is just a bunch of letters or sounds that go together in a certain order. The name itself is not me --- I am much more than a bunch of letters! The name *refers* to me. Or rather, since you know that my name is Jonathan, you know that when someone says "Jonathan" they are talking about me.

Now, in the real world, there are thousands, if not millions, of people named Jonathan. I am just one. The reason why you know that Jonathan refers to me as opposed to some other Jonathan is because of *context*, or in programming terminology, **scope**. That is, you can tell Python, "When I say 'Jonathan' I mean this guy, but only in this context" and Python has specific rules for when this Jonathan means me and that other Jonathan means someone else. These are called "scoping rules" and we'll cover them, because they're important. But not yet.

What's really going on underneath is that Python keeps track of all the names it was told about -- all the variables. It keeps a record of each name and attached to each name is a number. It uses a "dict" structure to do this, which is the perfect sort of structure for this sort of thing. Anyway, Python knows all the names you told it about, and when you talk about one of the names, it looks it up in the dict and it finds a number. That number is not the thing we are referring to, it is a memory address inside the Python program memory. At that memory address, if you were to look it up yourself, you would see a sequence of bytes and numbers that tell the computer not only what kind of thing is there but also what its value is. We can't store people inside computer memory yet, but we can store numbers. So let's walk through an example.

(NOTE: The >>> means that I am typing commands into the Python interpreter directly. Start up Python and type along with me.)

>>> a
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    a
NameError: name 'a' is not defined

You can type any name. I just chose 'a' since it is short. Go ahead and type 'Jonathan' or anything else.

NOTE: The rule is that variable names in Python must start with a letter or '_' and must only contain letters, numbers and '_'. By "letter", I mean pretty much anything in Unicode that is letter-like.

You should note that Python doesn't know what you're talking about. That's what the NameError is all about. In fact, it tells you: "name 'a' is not defined."

Now, if you typed in something it already knows about, it is going to tell you what that is. Try typing this:

>>> min
<built-in function min>

"min" is something Python starts off knowing about. Now, you can tell it to forget all about 'min' and call min something else, and I often do things like that for some things, but usually, it's a bad idea. The reason is that 'min' and other functions like it are very useful, and people expect it to do something specific, and if you go around changing it, then they get confused. So don't do that.

How do we teach Python about new things? We use the assignment statement.

>>> a = 5

Now, I told Python, "'a' refers to 5." I did *not* tell Python that 'a is 5'. There's a subtle yet important difference here. Just like the word "Jonathan" is not me, but refers to me, Python keeps track of what 'a' is referring to. The '5' exists somewhere inside of Python's memory, and 'a' only contains a number telling Python where it is.

We can now ask Python what 'a' is:

>>> a
5

Magical, isn't it?

Pretty much anything you could do with 5, you can do with a.

>>> 5*2
10
>>> a*2
10
>>> 200/5
40
>>> 200/a
40

You might get excited and hope Python can solve your algebra homework for you:

>>> a/5 = 10
SyntaxError: can't assign to operator

This is a fairly mysterious error but if you think about it, it makes sense. See, 'a/5' says "divide a by 5". So really, you are saying "divide a by 5 now means 10". Well, Python says you really can't go around telling it what divide means. So it says, "can't assign to operator" (divide is an operator.)

So no, Python can't do your algebra homework. But it can do parallel assignment:

>>> a, b = 5, 10
>>> a
5
>>> b
10

This doesn't seem that amazing until you do something crazy like this:

>>> (name, (age_min, age_max), (ideal_weight, actual_weight)) = ("Jonathan", (35, 40), (220, 250))

This is a feature of Python that most languages don't have: Structured assignment. You're going to find you need this particularly as you deal with complicated data structures.

function definitions

You'll probably see code like this everywhere:

 def integrate(z, b):
     """Integrates z with b over some interval."""
     z += 7-b

This is a Function definition. Functions are the first major concept you have to grasp. Or rather, the second.

if block

for block

while block

try block