In the last post we talked about Python strings and string concatenation. We even saw how we can get user input and use it in our program. But the use was very limited. If we want to do more we need to tell our programs how to make decisions. For that we need if statements.
Let’s have a look at the greeting program from last time:
print "What's your name?" name = raw_input() print "Hello " + name + "!"
The first line simply prints a string, the second line gets user input, and the last line prints a concatenated string. That’s all fine and dandy but the program is still kinda dumb, I mean you could say your name was “zoosmell pooplord” and the computer wouldn’t know the difference.
What's your name? zoosmell pooplord Hello zoosmell pooplord!
Let’s make a little addition
print "What's your name?" name = raw_input() print "Hello " + name + "!" if name == "zoosmell pooplord": print "Hey wait a minute! That's not your name is it?!"
Now let’s try it again:
What's your name? zoosmell pooplord Hello zoosmell pooplord! Hey wait a minute! That's not your name is it?!
Buh-wuh-buh? The computer is not fooled by my ruse? Maybe I should try being honest with the computer, at least for now…
What's your name? Steve Hello Steve!
I’m not sure I’m comfortable with the computer knowing so much about me….
Ok, let’s break this down. What’s going on with these last two lines?
if name == "zoosmell pooplord": print "Hey wait a minute! That's not your name is it?!"
The way if statements work is that they first test for a condition and then, if the condition is true, execute all the indented code underneath them. Python is a bit unique in that it uses indentation to determine what’s underneath an if statement. When you study other languages, you’ll find that they use other ways, but the bottom line is always this: if statements test for a condition, if the condition is true then the code within the if statement is executed. If the condition is not true then the condition is not executed..
In our case the condition is name == “zoosmell pooplord”. That double equals inbetween name and “zoosmell pooplord” is what’s called a comparison operator. We’ll talk more about them in later posts, but this one, the double equals, is checking if the thing on it’s left is equal to the thing on it’s right. If name is equal to “zoosmell pooplord” then the program prints our indignant message. If name is not equal to “zoosmell pooplord” then the indented code is not executed.
Also, and this is important, don’t forget to put a colon at the end of your if statements or they won’t work!