Conditional Statements Sometimes in programming you need to ask certain questions and have the program respond accordingly. You can do so with conditional statements. Basically the way they work is like this: "If this, then that." They get more complicated of course. You also can say "If this happens, do this, else do that." Or even If this and That, or This or That, then do this else do that or that. If Statements The If Statement simply says: "If this, do that." Here is how that looks in code: Note: don't forget that with Python you MUST indent. #!/usr/local/bin/python name = “The Black Knight” if name == “The Black Knight”: print “I'm not dead yet!” The above code creates a variable named (oddly enough) name. It then stores the value “The Black Knight” in it. It then enters an If Statement, that says If the value of name is “The Black Knight” then print “I'm not dead yet.” If not, do nothing. In this instance, the criteria is met and so the following is printed to the screen: I'm not dead yet! Pretty simple right? But obviously lacking in what the poet JJ (aka Jimmy Walker) would call DYN-O-MITE...ness. What if the name wasn't the Black Knight? For that, you would need to use our good old buddy the Else Clause. #!/usr/local/bin/python name = “The Purple Knight” if name == “The Black Knight”: print “I'm not dead yet!” else: print “Now I am dead.” Since the value of name is not equal to “The Black Knight”, the program continues on to the else clause and prints the following text to the monitor: Now I am dead. Before we get into the next Conditional Statement, let's take a look at a few operators. Check out the table below:
blog comments powered by Disqus |
|
|
|
|
|
|
|