Alright, you know how to produce output, do math, and you know about Python's type system. But here's the problem: all of the programs you currently know how to write can only do one thing. You can write a program that does A, then B, then C, but you haven't yet learned to write a program that can do A, then, depending on the results of A, either B or C. That's where this chapter comes in. If you want the Computer Science-type official sounding terms for what this chapter is all about, the main subjects here are if/then and branching, but there will be a small diversion into the concept of scope as well.

But first, here's the big idea. You don't want to do the same thing every time. You want to have a different behavior depending on what the user inputs, what the file contains, what various functions return, how big a number is after you multiply it... any condition, really. The syntax for this behavior is:

if condition:
    actions
The above line is a computer scientist's way of saying if the condition is true, then perform the actions. This notation can be extended as well. We can for example add an "otherwise", also know as an else clause into the mix. This would give us:
if condition:
    actions
else:
    different_actions
This translates into the english sentence: if the condition is true, then perform the actions, otherwise perform the different_actions.

Boy is this ever useful - now your code can do different things based on the data you give it. You can test for equality, greater than, less than, non-zero-ness, anything at all! Here's an example that will illustrate the point:

name = raw_input("What is your name?")
if name == 'Jongleur':
    print 'hey, you wrote this'

else:
    print 'Your name is', name
You can even make a (stupid) game!
number = 7
guess = raw_input("What number am I thinking of?")
if guess == number:
    print "You got it!"
else:
    print "Sorry, I was thinking of", number
(Exercise for the reader: What does this "game" do?) (Another Exercise: Why wouldn't you want to play this game more than once? Try fixing that by using the randint(int, int) function in the random library. This is pretty advanced, actually, which means that this exercise is entirely optional, and the reward is a gold star. Kind of like when your first grade teacher asks the class to spell February.)

You can test anything for any quality, but some things only make sense in particular contexts. This is an example of the type system at work. It makes sense, for example, to check whether a string is equal to another string. It makes very little sense to check whether a string is greater than or equal to the floating point number 3.1415926535. You compare two things for equality using the == operator, not the = operator. Note that there are two equals signs here because only one equals sign means "store the value in", and you want something that means "check whether these two things are equal". This messes a lot of people up, and a very common bug is to perform an assignment when you mean to check for equality. Fortunately, Python catches this error, unlike a lot of other programming languages that don't. Strings are false when they are empty. This means that the following code:

 
str = ""

if str: 
    print "str is true" 
else: 
    print "str is false"
will print out false. Similarly, uninitialized objects, arrays with a length of 0, empty dictionaries, and closed files are all false. You can use all of the comparison operators you learned about in school: <=, >=, <, and > are all valid things to put in your test clause. Using parentheses for grouping and and, or, and not you can chain conditions to make huge conditions out of small ones. One example of this might be:
if ((1 < 2) and (4 < 3)) or (not (5 < 4)):
    print "It all ended up as true"
else:
    print "it all ended up as false"
If the example above looks tortured and hard to follow, that's because it is. Take it step by step and you should be fine. If you are having trouble telling which statement will execute (which line of code will get run), I recommend you code it up on your own and find out! (The answer is pipelinked here for the impatient) Play around with these - if/then clauses are incredibly useful, and are pretty fundamental, so you should be very comfortable with them before you move on to the next chapter.

Speaking of moving on, I haven't yet dealt with scope yet. Scope is the idea that not every bit of code can see every variable. At first this seems counter-productive: "but what if I NEED that variable?". I promise that as your programs grown in complexity, you will be very thankful that this concept exists. The following code is an example of code that uses scope to hide variables from areas that need not know about them:

str = raw_input()

if str == "foo":
    print "give me another string"
    newstr = raw_input()

    if newstr == "bar":
        print "Be more original.  Bad nerd puns are not valid input" 
    else:
        print "You input", str, "followed by", newstr    
else:
    print "You input", str
This code doesn't do a whole lot, but you might imagine putting some complicated stuff inside that if clause. Now, if you ever later wanted to use newstr, you'll find that you can't! That is because you only declared newstr (that is, the first line on which newstr is mentioned) is inside the if statement. This means that the variable doesn't exist outside of that statement. At first you might think of this as an annoyance, but consider this: what if I could use newstr later, but str was not equal to "foo"? newstr wouldn't have any value set! It would be a null object, and we wouldn't know what to make of it. It just wouldn't make sense.

That logic of "it just wouldn't make sense" is the underpinning idea of scope. You can think of the inside of a block (a CS major fancy way of referring to a contiguous region of lines that are all indented at the same level) as a little mini-program in itself. Once that mini-program is done, all of the stuff that only it used is thrown away. This means that newstr is undeclared, and if you tried the following, you will get an error:

str = raw_input()

if str == "foo":
    print "give me another string"
    newstr = raw_input()

    if newstr == "bar":
        print "Be more original.  Bad nerd puns are not valid input" 

print "You input", str, "followed by", newstr
This is because of that scope thing again. Only the inside of the if statement knows anything about newstr, so if we refer to it outside of that scope, Python will barf. Like all code listings, you are encouraged to try it to verify that I am not just blowing smoke.

So this chapter can be summed up as: If/then is a very cool and useful thing, but it can make things tricky. It is, however, essential to know how it works because every computer language has something that acts like it, so no matter what you end up doing, it will be relevant to understand.

The idea of code doing different things under different conditions, will become even more relevant in the next section, where I will try to explain how to do things more than once without writing the same line over and over again.

<< | Learn to Program | >>