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!

No comments:

Post a Comment