Python Conditionals, Lists, Dictionaries, and Operators (
Page 1 of 6 )
In our last article we learned how to get input from the user, store data in a variable, and work with some basic operators to manipulate that data. In this article we will learn to use Conditional Statements and possibly create functions. So wipe that mustard off your chin, clean the dishes, and let's get to work.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:
|
Operator |
What it Does |
|
< |
Less Than |
|
> |
Greater Than |
|
<= |
Less than or equal to |
|
>= |
Greater than or equal to |
|
“==” |
Equal to |
|
!= |
Not equal |
|
<> |
A different way to say not equal |