Monday, January 30, 2012

Lesson 2 - Integers and Functions

Integers

Last time, we learned all about strings and variables.  If you didn't see it, you find it here.

Today, I'm going to talk about integers—a term you may remember from mathematics.  An integer is a number with no fractional part.  3, 12, and 239487 are integers. 3.5, 7.32, and 0.45 are not integers; they are floating point numbers, but more on that later.

Open the Python command line interpreter.  If you don't remember how to do that, check out the first entry of this blog (found here).


Now that it's running, assign an integer to a variable like so:

myInteger = 10

Notice the lack of quotation marks.  That's because this variable is going to hold a number and not a string.  You could get the string "10" by doing this:

myString = "10"

Now if you print each variable

print myInteger
print myString


you aren't going to notice much difference (at least not right away).  (Note: The two lines above should be entered separately.  Don't try to enter them on the same line or there will be problems.  Whenever I put multiple lines together, just enter each one separately and hit return or Enter after each one.)





So what's the difference you ask?  Try this:


print myInteger + myInteger
print myString + myString



Whoa?  What happened?  10 + 10 ≠ 1010!  What happened?

Remember in Lesson 1 when we learned about string concatenation (from Latin meaning "linked together")?  That's what happens when you use the plus (+) sign with strings.  Instead of adding the values, it just puts one right after the other.

I'm sure someone out there is wanting to try this, so let's try it together:

print myInteger + myString




Oops an error!  Why can't we add or concatenate them?  It's because they are two different types.  A type is a kind of data.  A string is a type; an integer is another.  Unlike some other scripting languages, Python cares about what type your variable is, but unlike some other languages, you don't have to come out and say what type it is before you assign (with the equals(=) sign) it.  Once we said that myInteger equalled an integer, it's an integer.  If we reassign it like so:

myInteger = "Getting Started with Python"

suddenly it's a string.

It is possible to convert between types, and that leads me to our next topic


Functions


A function is a piece of code that exists somewhere else.  You pass variables to it, and it returns a value back.  For now, we are only going to deal with functions built-in to Python, but eventually, we are going to write our own functions.

The functions we are going to talk about first are these two:  int() and str()

A function call has two parts: the name of the function (eg int) and the parameters (whatever goes between the parentheses).  Some functions take no parameters, and some take a specific number of them in a certain order.

The int function takes one parameter and returns an integer representation of that parameter.  Let's try it.  First, let's make a string version of some number.

string = "42"

Now let's say we wanted to print the variable string with the number 1 added to it.  If we try

print string + 1

we get an error.


Why?  Because string is a string, and integers cannot be added to it.  What can we do?  Functions to the rescue!

We are going to call the int() function.  To do that, we put our variable between the parentheses.

print int(string) + 1


Tada!  It worked!  The function int() converted our string to an integer and then added one to the result.

For sake of learning, type this:

print string



Surprised?  Why does string still equal "42"?  That's because we never actually changed string, we just accessed its value.  In order to change string, we have to do something (like assign it) like this:

string = int(string) + 1
print string



Whoa!  What did we just do?  Remember the equals(=) sign isn't the same here as it is in mathematics.  In algebra, x = x + 1 has no value for x that will balance the equation.  In programming it's perfectly legal.

Here's what happened:
  1. Python converted string to an integer with the int() function.  It doesn't assign it just yet, but it remembers the integer 42 that int() returned.
  2. Python added 1 to 42 giving us 43.
  3. Python assigned the integer 43 to the variable string.
So is string still a string?  No, it's now an integer.  (How ironic!)  How can we be sure?  There's another function called type() that will tell us what type the value stored in a variable is.  Type this:

print type(string)



Aha!  <type 'int'> tells us that it's an integer.  What if we want a string?  Another function to the rescue!

string = str(string)
print type(string)



Voila!  The variable string is a string again!

Now let's try what we just did all at once.  (Yes, we can do that)  Don't panic, just follow me.

First, let's set string back to "42"

string = "42"


Now let's write our code to do what we want to do to that value:


string = str(int(string) + 1)


Now let's see what happened:


print string
print type(string)



It worked!  Don't worry if it looks complicated.  We just did the same thing we did above only this time we did it all at once.  Here's the breakdown of what happend in the line string = str(int(string) + 1):
  1. Python converted string to an integer with the int() function.  Again, it doesn't assign that value to string; string is still "42" at this point (and will remain so until #4)
  2. Python added one to the integer 42 that it remembered and got the integer 43
  3. Python converted the integer 43 that it was remembering to a string using the str() function.
  4. Python assigned the string "43" to the variable string.
Yes, that one line of code did all that.  Makes sense doesn't it?

But how did Python know what to do first?  Just like in mathematics, programming languages use parentheses to indicate what should happen first.  (It's actually a little more complicated than that, but don't worry about that now.)  It starts in the innermost parentheses and moves outward.


Documentation

How do we know what parameters functions like int() take?  We look at the Python documentation found here.  This is where you can find out many things about the Python language, including built-in types and functions.  To save you the trouble of finding it, the int() function is documented here.

Don't worry too much about what it says.  All it means is that we can convert other types to integers provided that the type is able to be converted.  To give an example of a bad conversion, type this:

print int("A")



Another error!  This was an error thrown by the int function to say that we did something wrong.  This is a good thing because otherwise it would have to pass back the integer 0, and that could have repercussions throughout the rest of our code.

A Word of Caution

At this point, I want to warn you to be careful when choosing your variable names.  You don't want to use variable names that are reserved (used by Python).  The cool thing about Python is that you can still do it, but it will mess up your program.  (If you do happen to overwrite something, don't panic.  The next time you start Python, everything will be back to normal.)

For instance DO NOT type something like this:

int = 10

This will get you into trouble because int no longer stands for a function; it stands for the number 10.

print int
print type(int)

Uh-oh!  We can't use int as a function anymore.  (I'm not sure quite how to get it back without quitting Python and starting it again.  Even so, doing that is beyond the scope of this blog.)


Math Operations

One last thing while we're still talking about integers.  Here's how you do simple arithmetic in Python:

print 3 + 3
print 3 - 3
print 3 * 3
print 3 / 3



The first two lines are obvious, but the next two may not be.

Addition: +
Subtraction: -
Multiplication: *
Division: /

There you have it, and you can use these symbols on integer variables too.

myInt = 7
print myInt * 6
myOtherInt = 3
print myInt * myOtherInt



And that's all for now.  Sorry it was so long, but I got a lot into this lesson.  If you're having difficulty understanding it all, try working through this post again piece by piece.

That's all for now!  See you back here for Lesson 3!

Review

  • Integers and strings are separate types in Python.
  • You can perform math operations on integers just like a calculator.
  • Functions are pieces of code stored elsewhere in your program.
  • Functions are called by placing parameters inside parentheses after the function name.
  • The int() and str() functions can convert other types to integers and strings respectively.
  • You can perform several functions on one line of code using parentheses.
  • The Python documentation contains useful information on functions and types in Python.
  • The standard math symbols in Python are + (addition), - (subtraction), * (multiplication) and / (division).






Saturday, January 28, 2012

Lesson 1 - Print and Variables

The Structure of a Python Program

Python programs read from top to bottom with (typically) one command on each line.  There are many commands you can use, and we'll start out very simply.

Before we go on, let me say first that the sort of programs you will write (at least at first) will be small and non-graphical.  Graphics take a great deal more time, and a lot more programming.  BUT that being said, the basic programming you will learn here can point you in that direction.  I hope that this blog will continue long enough to get to the point where I can show you the way I made games on my website.

The print Command

The first language I learned was called QBasic, and the very first command one learns in BASIC (more often than not) is the print command.

All right.  It's time to fire up the Python interpreter.  (If you don't remember how to do that, click here.)



I'll be using my Mac for now.  Maybe later I'll switch over to a Windows machine.

Time to write your very first line of Python script ever!  Simply type (or copy and paste):

print "Hello World"

and hit the return key (or the Enter key).




Ta da!  Python executed your line of code!  The "print" command simply writes something out to the console.  (The Terminal or Command Prompt window is called the "console.")


The "Hello World" part of that command is called a string.  A string is simply a "string" of characters (letters, numbers, and symbols), whether its one character or a billion.  You'll be using strings a lot in programming, mostly because that's the way that you store and display words.  Strings are always indicated by quotation marks, whether double-quotes ("Hello World") or single-quotes ('Hello World').


Variables

Don't worry.  This isn't algebra.  A variable is a container for a piece of data (like a string).  Unlike algebra where you're solving for variables, you get to tell that variable who's boss.  To assign a variable, you can simply do something like this:

a = "Hello World"

Unlike math class, the single equals(=) sign tells Python to store the string "Hello World" into a variable called a.  Now you can do something like this:

print a

Notice how I didn't use quotes.  We don't want to print the letter "a"; we want to print the string stored in the variable called a.  Here's what your console (remember that term?) should look like:


Now if we try the command (notice the quotation marks)

print "a"

we should get this:


See how it printed the string "a" instead of the string stored in variable a?

Variable names don't have to be single letters; they can be full words.  A variable name can include numbers, letters, and certain symbols (most commonly the underscore (_)) provided the variable does not begin with a number.  For example, type this into the interpreter:

myString = "This is a string."

Now print it to the screen using

print myString



See how that works?  Variable names help you keep track of what the variable is used for.


Concatenation

Now what if you want to type two strings at the same time?  Simply use the + sign.  When used on two string, Python puts one string directly after the other to form a new string.  Type

print a + myString

and you should get something like this:



This is called concatenation (from Latin meaning "linked together").

You may be wondering why there is no space between the word "World" and the word "This"; this is because you did not have a space at the end of "World" and Python just put together what was there.  To add a space, you can type something like this:

print a + " " + myString



You can also assign this new string to another variable.

newVariable = a + "! " + myString

(Notice how I added an exclamation point in there.)  Now you can type

print newVariable


An important thing to remember about variables is that they are case-sensitive (capital and lowercase letters matter).  Try typing this:

print newvariable



Aaaaaaah!  What happened?  Congratulations, you just experienced your first error.  Don't worry about what it says; simply put it means that you tried to use the variable newvariable when it didn't exist.


Review

That pretty much wraps it up for Lesson One.  I hope it wasn't too confusing.  By way of review, here's what you should have learned:
  • The print command puts information on the console.
  • Strings are strings of characters surrounded by quotation marks.
  • You can use single-quotes (') or double-quotes (") to indicate a string.
  • You can store strings in variables.
  • Variable names are case-sensitive and can be made up of one or more letters, numbers, or symbols.  (Variable names cannot start with a number.)
  • Variable names cannot start with a number.
  • You can concatenate strings using the plus sign (+)
That's it!  See you next time!

First Things First

First of all, let me say that the reason I'm doing this is because I feel that everyone (or at least everyone using a computer) should be familiar with computer programming.  Everyone uses software written by other people, but what happens when there's no piece of software that solves a specific problem?  I've used Python before to write scripts to help make data more readable or to save me the trouble of long and tedious data manipulation.

There was one time I was given a spreadsheet with thousands of names.  Each name was in its own line with the full name written into one cell with the first name first (like "John Smith").  The trouble was that the names weren't sorted and they needed to be . . . by last name.  So, I could have spent hours splitting up the names, but instead I wrote a Python script to do it for me.  I am firmly opposed to doing tedious jobs manually (especially on computer) when a machine (or program) could be devised to do that job automatically.

That's just one reason I want to write this blog.  Another is that programming helps people become better computer users.  Programming will give you a better understanding of how your computer works.

Now that that's out of the way, onto lesson one!

A Very Good Place to Start

Everyone (or almost everyone) uses software written by other people. Your operating system, the browser you are using to look at this page, the music player you have open–all of these were written by someone else. (Unless of course you wrote part of them, in which case this blog is not for you.)

A sad reality I've had to face is that no one really cares about computer programming. Programming is something done by other people wielding powers the first group doesn't often understand.  But don't panic; it can be learned.

You may have heard of the languages of C++, Python, Java, or PHP. There are numerous others, but for the purposes of this blog, I'm going to focus on Python. Python is easy to use and very powerful, and the forced-indentation (don't worry; I'll explain what that means later) creates good programming habits. Python is also a strictly(ish) typed language (unlike PHP or Javascript), but I'll talk more about that later.

There's so much that I want to say about Python, but I don't know where to begin. For this first post, let me tell you where you can find Python.

Windows

For Windows users, you will need to download and install the Python Windows Installer found on this page: http://python.org/download/

At the time of this post, the most recent version is 2.7.2. Yes, I know there's a version 3.2.2, but it's a bit different so we won't deal with that here. The link you want to download looks like this:


This is the 32-bit version.  It should still work on 64-bit systems, but if you really want to, try the "Windows X86-64 Installer" below it.

Now just walk through the installation, and let it install where it wants to.



When you're done, open the Command Prompt. If you're on Vista or 7, you can just type "Command Prompt" into the search on the start menu, and it will find it for you. If you are on XP or lower, go to the start menu and select "Run." In the box that appears, type "cmd" and press Enter. You will now get something that looks like this:



To run Python, you should be able to type "python" and press Enter. The window should then look like this:



This is the command line interpreter. Type in 2 + 2 and hit Enter and see what happens. Don't worry; this is not just an overblown calculator, as we shall soon see.


Mac OS X

Mac OS X comes with Python preloaded. To run it, all you have to do is go to the Terminal. To get there, go to Spotlight in the upper-right corner of your screen and type "Terminal" into the text field. The top hit should be an application of the same name (ie Terminal). Open it, and you should get something like this:



Now simply type "python" and you should get something like this:



Again, this is the command line interpreter. Type an expression like 2 + 2 and hit return, and you should see the number four appear below it.



Linux

Like Mac OS X, Linux comes with Python preloaded. But odds are if you are using Linux (or any other OS), you are already beyond the scope of this blog (at least for the foreseeable future).


That's it! Python is up and running, and you're ready to start your programming journey!