Saturday, February 18, 2012

Lesson 5 - Input and If


So far, we've learned how to set up variables and print them to the screen.

So now, create a folder called "Lesson 5" in your python directory (which we set up in Lesson 3).  Open a new console window and navigate to that new folder so you're all ready when the time comes.

NOTE: Before you continue, look at this blog entry to learn how to set your tabs and indentation.

Now open your text editor and create a new file and give it a good name (like "").

All right, now we will write our program.

First, let's talk about input.  Input is when you the user send some kind of to a program.  In the programs we will write at present, this is done via the keyboard.

The simplest way of getting input is by using the raw_input() function.  The raw_input() function waits for the user to type something and press return or Enter, and it then returns that input as a string.

For example, open the Python command line interpreter in the console.

Now type this:

string = raw_input()

Whoa!  What's happening?  The cursor is just sitting there.  What's it doing?  It's waiting for you to type something.  Go ahead and type

Python is great

and press return or Enter.

Okay, now we're back with the familiar three greater-than signs (">>>").  The string "Python is great" was just assigned to the variable string.  To prove it, let's type

print string

See?  It worked.

Now the raw_input() function has something called an optional parameter.  You remember parameters—those things that go between the parentheses ().  Well raw_input() can operate with or without a parameter.  In this case, it takes a string that will print on the line before your input begins; in other words, it's a custom prompt.  To see what I mean, type this:

string = raw_input("type something>")

See how that string "type something>" appears before the cursor?  This can be useful for telling the user what sort of information you're looking for.

Now before you type anything, press return or Enter.  Can you guess what the value of the variable string is now?

print string

Hmmm . . . there's nothing there.  That's because the variable string is currently set to an empty string.  An empty string (which you can represent as "") contains no characters and has a length of 0.  To be able to see that it does in fact contain nothing, type

print ">" +  string + "<"

See?  There's nothing between the "><" we printed out.

Now then, let's return to our program.  In your "" file, type these lines at the top:

print "What is your name?"
myName = raw_input("name>")

When we run this program, we will have a string in the variable myName.  Now what are we going to do with it?

The if Statement

Now we get to the heart of programming—the if statement.  The if statement is what makes programs work.

Before we go any further, let's talk about booleans (sometimes capitalized because it comes from a name–George Boole.  A boolean is a special type that contains one of two values—True or False.

Go back to your console and type

b = True
print b
b = False
print b

The True and False being printed out are not actually the strings "True" and "False"; that's just how print renders them.  Pop culture is obsessed with the idea of 0's and 1's in regard to computers; well, here you have them—0 or 1, on or off, true or false.

Besides actually assigning the literals True and False, you can also use comparisons.  Like this:

i = 10
b = i < 20
print b

Cool!  It worked!  We can use the less-than (<) or greater-than (>) signs just like in mathematics.  (If you use them on strings, I think it will try to compare them as if you were trying to sort them).

What about equality?  The equals sign (=) is already used for assignment.  What do we do for testing if values are equal?  Well, we use the double equals operator (==); two equals-signs back to back.

b = i == 10
print b

Tada!  Be careful though; even experienced programmers will ever now and then forget and put a single equals sign where a double equals should go.  You can get some really interesting results.

Incidentally, you can also use less-than-or-equal-to (<=) or greater-than-or-equal-to (>=) as well.  This isn't so important for integers, but it's crucial for floats.  Another really important comparison operator is the not-equal-too (!=) sign.  (If you do something like "c = a != b", c will be False if a and b are equal, and True otherwise.)

Now then, back to if statements.  We can use if statements to evaluate booleans or expressions that return booleans (like those comparisons above).

Go back to our program, and type this line:

if myName == "":

In that line, we are wanting to compare the string in variable myName to the empty string.  If myName is the empty string, we want to do something.  Here's how we do it:

if myName == "":
  print "You did not enter a name"

Notice the two spaces before the print statement.  (I actually pressed the TAB key to do this, though you can use spaces if you wish.  If you followed the blog entry about setting up tabs and indentation, this will happen for you too).

Why are the two spaces there?  It's to let Python know what statements to run if the if statement resolves to True.  This is called a block of code.  C-style languages use curly brackets ({}) to set-off blocks.  Like if I were in PHP, I would right something like this:

if($myName == "") {
  print "You did not enter a name";

Don't get too thrown off by the different syntax; suffice it to say that making sure that you know what code is going to run when is very important.  I indented the code above even though I didn't have to because it makes code more readable.  That's the great thing about learning Python; it forces you to become a good code formatter.

But anyway, back to Python.  Now that we've tested for the empty string and printed something if it tests positive, what if we want to do something if the variable myName is not the empty string.

We could type something like this after the first if:

if myName != "":
  print "Your name is " + myName

That works for now, but what if we altered the first if to be

if myName == "":
  print "You did not enter a name"
  myName = "Nemo"

Then the second if would always be true.  We only want it to run if the first if was false.

Incidentally, setting myName inside the if block is perfectly ok.  It doesn't cause the if to evaluate to true again.  Once you're inside the block you stay inside the block.  (There are ways to prematurely leave a block, but I'll get into that later).

So what do we do instead?  Well, there's a statement called else that we can use like so:

if myName == "":
  print "You did not enter a name."
  myName = "Nemo"
  print "Your name is " + myName

There, now that should do what we expect.  Even though we set myName to something other than the empty string, the else will be skipped.  Just to be sure that myName is getting set, let's print it at the end of the program.

print myName

Now it's time to run our program!  Leave the Python command line interpreter by typing "exit()" (or if you read this blog entry, you can type the appropriate end-of-file shortcut (ctrl+D on Mac and ctrl+Z on Windows).  You can also clear your screen using the "clear" (Mac) or "cls" (Windows) commands.

Now, assuming you're still in your "Lesson 5" folder, run your program by typing


(or whatever your filename is)

When prompted for a name, just hit return or Enter, and your program should run the appropriate code

Now run it again (you can press the up key and get the last command you entered)


and this time enter a name.

Ta da!  It worked!


Well I think that's it for now.  There's a lot more I want to cover, but I'll save that for the next lesson.  Here's what we learned in Lesson 5.

  • The raw_input() function returns a string that the user types in when the program runs.
  • The raw_input() function takes an optional parameter to define a prompt.
  • Booleans contain one of two values—True or False
  • Comparison operations return boolean values that can be assigned to variables.
  • An if statement uses a boolean to run a certain code block if the boolean value is True.
  • The else statement runs certain code when the if statement above it is False.
  • Assigning variables inside if blocks does not alter the execution of an if block's code.

That's it!  See you later!

Tabs and Indentation

Setting Up Your Text Editor

Indentation (whitespace (spaces and tabs) before text) is very important in Python.  It helps define where blocks of code begin and end.  For the purposes of this blog, we're going to need to set up your text editor.

I'm going to show you how to change your tab settings in both Notepad++ (Windows) and TextWrangler (Mac).  If you are using a different editor, don't panic.  Doing this is very common and a quick Google search should show you how to do it in your editor.


Open Notepad++ and go to "Settings" on the menu and click "Preferences."

On the window that appears go to the tab labelled "Language Menu/Tab Settings."

Under the "Tab Settings" frame, make sure "[Default]" is selected.  In the lower right corner, check the box that says "Replace by space" and then set the "Tab size" to 2.

Click close and you're ready to go!

Text Wrangler

Text Wrangler is a bit more tricky, but it's still easy enough.  With Text Wrangler open, go to the "Preferences" entry under the "TextWrangler" menu.

A window like this will appear.

On the left, click on the line called "Editor Defaults."

Now, check the box next to "Auto-expand tabs."

Now go down to "Default font:" and click on "Set..."

A box like this should appear.

Set the "Tab Width" to 2 spaces

Now close that window and the Preferences window and you're all set.


Why did we just go through all that?  You'll see in the next lesson (Lesson 5)!

Console Shortcuts 1

Command Recall (Up Arrow)

When using the console (or command line), little shortcuts can save you a lot of time.  Here are some that will save you some time in the console (but not necessarily in Python).

The first is the up arrow.  Use this to bring up the last command you typed in.  Press up multiple times to keep bringing up more commands you entered previously.


Autocompletion (Tab)

Whenever you type in a filename or folder name (like in a "cd" command) and you don't want to type out the whole thing, just type in the first few letters and hit tab.  If there is only one file/folder that fits that name, it will automatically fill it in (with escapes (indicated by a backslash(\)) and/or quotation marks).  If there's more than one, what happens next is determined by whether you are on Windows or Mac OS X.  On Windows, it will start with the first match and cycle through the others as you continue to hit the tab key.  In Mac OS X, a list will appear of all the matches.  You'll have to enter more characters and hit tab again.

With a little practice, this one will save you a lot of time.

End of File (EOF) (Ctrl+Z (Windows) or Ctrl+D (Mac))

These are useful for exiting programs while they are running.  EOF is used mostly for long sequences of input to let the program know that you're done entering things.  If you ever need to exit and don't want to go through all the trouble of finding out how that particular console application exits, just hit the appropriate sequence (ctrl+Z in Windows; ctrl+D in Mac).

NOTE:  Do not hit Ctrl+Z in the Mac Terminal.  It will do something very different that's a bit complicated.  It's not the end of the world, but it's beyond the scope of this blog entry.

Interrupt (Ctrl+C (Windows and Mac)) 

There will come a time (most likely) when you write a program that contains a loop, and you make a mistake that causes that loop to run forever.  Your program is now running forever!  What can you do?  Hit ctrl+C.  This will send an interrupt signal to your program (actually I think it sends it to Python) and tell it to quit.  This one can really get you out of a jam.

Clear Screen Commands ("clear" (Mac) or "cls" (Windows))

Ever wanted to clear away everything that was on the screen and start at the top again?  You can with the "clear" (Mac) or "cls" (Windows) command.  On the Mac, the "clear" command doesn't actually get rid of what you've entered; you can still scroll up and see it.

Saturday, February 4, 2012

Lesson 4 - Floats and Lists


In Lesson 3, we learned about text editors and how to run Python script files.  (If you haven't done the setup, you may want to go back to Lesson 3 because you'll need to have all that done eventually.)  For this lesson, we'll use the command line interpreter until the end when we'll write a program.

So now, open a console window.  (If you don't remember how, look here.)

Let's cover floats really quick.  A float (or floating point number) is a number that contains a decimal portion.  In other words, a float is whatever isn't an integer (more or less).  To make a float, simply put a decimal point after the whole part of the number.  Like so:

print 12.4

Nothing to it, right?  Here's the tricky part.  What if you are dividing numbers?  Try this

print 3 / 2

Surprised?  Why did we get 1 as the answer?  That's because we were dividing with integers; when you divide with integers, you get an integer answer.  If you want the remainder, you can to use the modulus symbol (which is the % sign).

print 42 % 5

Great, but how do we get a floating point answer?  We have to use floats to start with; at least one of the operands (the numbers involved in the math operation) has to be a float.  How do we make the integer 3 a float?  Remember, this isn't like math class; this is programming.  We can simply do something like this:

print 3.0 / 2.0

Wait!  Aren't 3.0 and 3 the same number?  Well, yes and no.  They are the same number, but Python treats them very differently.  The decimal point is just your way of telling Python that you want this number to be a float and not an integer.

Now then, question: for representing currency (eg $1.40) in a program, should you use integers or floats?  Answer: you probably actually want to use integers.  Why?  You always know that there are two decimal places, so you just multiply everything by 100.  So $1.40 becomes 140.

The reason you would want to do this is because of something called round-off error.  See, in a computer,  floating point numbers are represented in a very special way, and sometimes weird things can happen (like this).  That being said, you'll probably be better off with integers in that situation.


Here's where things get interesting.  A list is just what it sounds like; you create lists of things like strings, numbers, and floats (and a lot of other things we'll get to later).  These items are sometimes called elements.  Unlike some languages, Python makes lists (often called arrays) really easy to make.  You create a list by using square-brackets [].  You can create an empty list like this:

myList = []

It stores this list with this variable.  An empty list isn't much good to us (at least not right now).  So let's create a list that has something in it.

myList = [1, 2, 3]

Now we have a list that contains the integers 1, 2, and 3.  Each entry is separated by a comma.  Now we can print that list.

print myList 

Ok great, but what good is it?  Well, we can access different items in that list by using square-brackets after the variable name like this:

print myList[2]

Tada!  The number 3!  But wait!  Isn't 3 the third item in the list?  Well sort of.  Lists are what's called zero-based, meaning that the "first" element is element 0.  Try it and see what I mean

print myList[0]

See?  That may seem a little weird at first, but it makes things WAY easier in the future, and once you start using lists this way, it becomes second nature to you.

You can also assign to a location in the list, provided the list already has something assigned to that position.  We can say

myList[1] = 17

but we cannot say

myList[5] = 17

See that error?  All that means is that we tried to assign outside the bounds of the list.

To get the length of list, you use the function len().

print len(myList)

Len takes one parameter, and returns an integer of its length.  The length of the list is 3 (because there are three elements in it).  Thus the last element of a list is always len(list) - 1.  It just takes some getting used to.

Incidentally, you can use len() with strings too.  The len() function counts every character (letter, number, or symbol) in the string (including spaces).

print len("Python is cool")

Only certain objects have a length.  What's an object?  Glad you asked.

Objects and Methods

An object is just a name for a group of information—like the information in a string or a list.  Most objects have cool things called methods.  A method is like a function, except you call it by placing a period(.) after the variable name.  The you put the method name, and last comes the parameters.  For example, a list has a method called append() which lets you add an item to the end.

myList = [1, 2, 3]
print myList

Voila!  You've called your first method.  Now remember that methods are particular to a specific object type (actually it's called a class, but more on that in another lesson).  Strings, for example, do not have an append() method.  Where can you find a list of the methods for a given object?  Check the Python documentation.  (Here's the ones for lists.)

There are many useful methods for each kind of object.  Be sure to check them out; they can really save you a lot of extra programming.

Integers and floats, however, are not objects.  They are called primitives.  They have no methods, and they are not stored by reference; they are stored by value.  Actually, that leads me into my next topic.


This may be hard to understand, but don't panic.   Variables are not objects; they point to objects.  This is commonly referred to as storing an object by reference.  In other words, when you say

myList = [1, 2, 3]

Python creates a list containing the integers 1, 2, and 3 in memory (you may have heard of RAM (Random-Access Memory); that's what this is; it's where your program stores its information), and then sets the variable myList to point to that list.  What does this mean for you?  Well, let's do this:

otherList = myList

What did we just do?  You may think we just told Python to make another list containing 1, 2, and 3 and assign it to otherList, but that's not actually what happened.  To demonstrate my point, let's append the number 4 to myList and then print otherList.

print otherList

Whoa!  Did appending to myList change otherList?  Not exactly.  Both myList and otherList point to the same object.  You can think about it like this:

The list is sitting off in memory somewhere, and both variables point to it.  So when you use the variable myList for a method call, what you're really saying is "take the object myList points to and perform this method."  Even though you have two variables, there's only one list object involved.

I know that sounds crazy, but it's how it works, and its really cool that it works that way because you can do some pretty cool stuff.  Now what if for some reason you wanted to copy a list, you have to use the function called list().

myList = [1, 2, 3]
otherList = list(myList)
print myList
print otherList

There we go.  Now we have two lists in memory.  When we used the list() function, Python made a copy of the list.  (Note: if that list contained objects, the objects are not copied only their references are, but I won't go into that now).


Now then what about strings?  Strings are objects; therefore they get pointed to (and not copied like numbers).  So can strings change like lists do?  Well, the truth is that there are no methods of strings that can cause strings to change.  So how do you use them?

Let's take for example the string method called upper().  It takes no parameters, and it's used to create a string with all uppercase letters.  (There's also a method called lower() which creates a string with all lowercase letters.)  Let's try called this method.

string = "This is a string."
print string

Huh?  Nothing happend?  Why didn't the string change?  That's because strings are immutable; they don't change.  This is good because you don't want to be changing strings around in one place and have things messed up in another.  So if upper() can't do anything to the string itself, what does it do?

Answer: It creates a new string and returns it.  A method (or function) can return something that you can store in a variable--either a primitive or a reference to an object.  Like the len() function we used above, it returns an integer of the length of the list or string, and we can assign it to a variable or print it or whatever we want.

Incidentally, that's why the string "THIS IS A STRING." appeared after you called upper().  In the command line interpreter, typing an object or primitive on a line causes the console to output a representation of that object or primitive.  (If you type in 2 + 2, even without a print statement, you'll still see 4).  So that string is not the value of the string variable but rather what was returned by upper().

To use upper() properly, you have to do something like this.

uppercaseString = string.upper()
print uppercaseString

See?  It works, but what if we wanted to have the string variable point to an uppercase version of itself?  Remember how assignment works?  It's not like math class, so we actually can do something like this:

string = string.upper()
print string 

No problem!  Python runs the method upper() on string object pointed to by the variable string, creating that new string object, and then it assigns a reference to that string object back to the variable string.  Make sense?

Let's Write a Program

Here we go!  Now we're going to write a program that uses everything we've learned so far.

We're going to create a list of words and then make each of them uppercase.

First things first.  Create a new folder in the "python" folder we created in Lesson 3.  Call this new folder "Lesson 4"; this is where you will save the new ".py" file we will create.

Speaking of which, open up your text editor.  (I'll be using TextWrangler on my Mac.)

Save this file in the "Lesson 4" folder we just made.  (A name like "" should do.)  Now we can start writing our code.

First let's do a really quick floating point example.  First, let's create a variable with the value for pi(π).

pi = 3.14159265

Now we can use the variable pi so we don't have to type it in every time.  Now let's do something like this:

print "A circle with diameter 7 inches has a circumference of"
print 7 * pi

Great!  But what if we want to add the unit "inches" after our answer, and put it on the same line?  We can't concatenate a number with a string, so we'll have to convert the number to a string first.  Replace the line

print 7 * pi

with this one:

print str(7 * pi) + " inches"

Yes, str() works on floats too.  That line will multiply 7 by pi and convert it to a string before concatenating " inches" on the end.  Notice that I put a space before the words "inches" so that we would get some separation between the number and the unit.

Now let's do the same thing, but for the area of a circle now.

print "A circle with radius 2.4 has an area of"
print str(2.4 * 2.4 * pi) + " square inches"

There, now that will calculate the area of a circle of radius 2.4 inches.

Now let's do some lists stuff, but first let's use the handy trick we learned from this blog entry.

print "-" * 80

That will print a line of "-" characters to give us some separation in our code.  Now let's create a list of strings.  Type this all on one line:

wordList = ["python", "programming", "two words", "This is a sentence."]

Notice how the commas go outside the quotation marks.  (If you are an English teacher, you're probably cringing right about now, but don't worry: it's not English; it's Python!)

Now let's do some cool by-reference stuff:

otherList = wordList

Now we're going to do a lot of things in one line.  We're going to get the item at index 0, convert it to uppercase, and then reassign it to position 0.

otherList[0] = otherList[0].upper()

Yes, we can do all that in one line.  We'd be in trouble if the object at 0 wasn't a string, but we already know it is, so it's ok.  Now let's do the same thing with all the other strings:

otherList[1] = otherList[1].upper()
otherList[2] = otherList[2].upper()
otherList[3] = otherList[3].upper()

Right now, you may be thinking that that's a lot of copy-and-pasting.  Surely there's a better way to do it!  Well, there is, and I think I'll cover that in the next lesson.  For now, let's just do it this way.

Now let's print the strings using the variable wordList.  We assigned the list at wordList to otherList, so it should have passed by reference, meaning that there is only one list involved here.  So if we type

print wordList[0]
print wordList[1]
print wordList[2]
print wordList[3]

we'll get the uppercase versions of the strings, even though we changed and assigned them using the variable otherList.

Now then, your full program should look like this:

pi = 3.14159265
print "A circle with diameter 7 inches has a circumference of"
print str(7 * pi) + " inches"
print "A circle with radius 2.4 has an area of"
print str(2.4 * 2.4 * pi) + " square inches"

print "-" * 80

wordList = ["python", "programming", "two words", "This is a sentence."]
otherList = wordList

otherList[0] = otherList[0].upper()
otherList[1] = otherList[1].upper()
otherList[2] = otherList[2].upper()
otherList[3] = otherList[3].upper()

print wordList[0]
print wordList[1]
print wordList[2]
print wordList[3]

Now for the moment of truth!  Open up a console window and navigate to the Lesson 4 folder we created by using the "cd" command.  (Consult Lesson 3 if you don't remember how.)  Now let's run it.  Type


and hit return (or Enter).

Voila!  Our program ran!  Take a look at the output (the stuff that printed to the console).  Is it what you expected?  First, we ran our calculations:

A circle with diameter 7 inches has a circumference of
21.99114855 inches
A circle with radius 2.4 has an area of
18.095573664 square inches

These answers are approximately correct.  We could get better approximations with a more precise definition of pi.

Then comes our line


And finally, the uppercase strings from our print statements


Pretty cool, huh?  We're well on our way to learning how to make the computer do work for us.  Right now we're just covering concepts, but it won't be too much longer before we can right a program that will do something useful.


That's it for now!  I know it's a lot to take in, but we'll be reviewing all this stuff along the way.  (Trust me; that object-reference thing is going to be in almost every lesson from here on out.)  Anyway, here's what we learned in this lesson:
  • Floats are numbers with decimals.  Python treats floats differently from integers.
  • To get a float result when performing a mathematical operation, at least one of the operands must be a float.
  • When you divide with integers, the result is an integer.  You can get the remainder of an integer division by using the modulus (%) operation.
  • Lists are ordered collections of elements.
  • Lists are zero-based, meaning that its "first" element is at index 0.
  • You access elements of a list by using square-brackets [].
  • The len() function can be used to get the length of strings and lists.
  • An object is something like a string or a list.  It usually has methods which sometimes perform operations on the object and/or return an object or primitive.
  • Objects are also stored by reference, meaning that two or more variables can point to the same object.
  • Primitives are like integers and floats.  They have no methods, and they are stored by value.
  • Strings are immutable objects; they don't change.  String methods that would be used to modify a string instead return a new string.
That's it!  See you next time!