Python Conditionals, Lists, Dictionaries, and Operators

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

{mospagebreak title=Elif}

The Elif works like the Else If in other languages. It states that if the original If statement is False, and then the Elif part is true, to do this. Here it is in code:


#!/usr/local/bin/python


beers = 100



while beers != 0:

beers = input (“How many beers are on the wall?”)

 

    if beers >= 1 and beer <= 20:

        print “Almost there. Take one down and pass it around!”

 

    elif beers >=21 :

        print “You got a lot of drinking to do!”


print “You should seek help!”

This program starts off creating a variable named beers. It then assigns the value 100 to it. Next, it creates a loop, that will continue looping while the value of beers is not equal to 0. Next it goes into an If statement that asks the user how many beers on are the wall. It then takes whatever numeric value the user enters and stores it in the beers variable. If the value is 0, it will exit the loop and print “You should seek help!” If the value is between 1 and 20 (greater than or equal to one AND less than or Equal to 20), it will print: “Almost there. Take one down and pass it around!” and continue through the loop. If the user enters a value equal to or greater than 21, it will print “You got a lot of drinking to do!” and once more continue through the loop.

{mospagebreak title=Lists}

We covered variables in our previous tutorial. Now we are going to cover Lists. You may have heard of arrays in other programming languages; a list is the Python equivalent. Whereas a variable holds a value, a list holds a bunch of values. Each value can be referenced by its position in the list, starting with the number 0 and moving forward. Here is an example:


#!/usr/local/bin/python


suess = ['I', 'like', 'green', 'eggs', 'and', 'spam']


print suess

print suess[0]

The above program creates a List named suess, and assigns a bunch of data to it, separating each piece of data with a comma (,). It then prints the entire List, and finally prints one element in the list, in this case the first one (0). Here it is!

  I like green eggs and spam

  I

You can also change the value of an element in a list later on:


#!/usr/local/bin/python


suess = ['I', 'like', 'green', 'eggs', 'and', 'spam']

print “This is the data in the list originally:”, suess


suess[5] = ‘ham’

print “This is the data in the list after the lawsuit:”, suess

Again, we fill up our suess List with data. Then we print it. Next, we change one specific element in the suess List from spam to ham (remember the first element is 0, so spam would be element 5). We then print it out with the new data, like so:

  This is the data in the list originally: I like green eggs and spam

  This is the data in the list after the lawsuit: I like green eggs and ham

The number of elements in a list is not a set number; you can add and delete elements until the cows come home. And let’s face it, once those cows have had a taste of the good life, they are never returning to your crummy studio apartment.


#!/usr/local/bin/python


suess = ['I', 'like', 'green', 'eggs', 'and', 'spam']

print “This is the data in the list originally:”, suess


suess[6] = ‘yummy!’

print ‘Here is the list with appended elements:’, suess

This results in:

  This is the data in the list originally: I like green eggs and spam

  Here is the list with appended elements: I like green eggs and spam yummy!

{mospagebreak title=Tuples}

Another way to store more than one piece of data is through tuples. Tuples work exactly like lists, except the data within them cannot be changed. And you assign value with parentheses instead of brackets. Observe!


#!/usr/local/bin/python


suess = (‘I’, ‘like’, ‘green’, ‘eggs’, ‘and’, ‘spam’)


print suess

print suess[1]

Resulting in:

  I like green eggs and spam

  like

You will notice that you still access an element with the brackets.

{mospagebreak title=Dictionaries}

Another way to store multiple values is with a dictionary. The difference between a List and a dictionary is that dictionaries are unordered and do not use indexes. The best way to understand them is to see them at work:


#!/usr/local/bin/python


mydiction = {‘FirstName’:'John’, ‘LastName’:'Cleese’}

print mydiction[FirstName]

The above code will result in the printout:

  John

This is because the value to the left of the colon (:) acts as the index, while the value to the right of the colon acts as the value being referenced.

You can also add two dictionaries together:


#!/usr/local/bin/python


mydiction = {‘FirstName’:'John’, ‘LastName’:'Cleese’}

abc = {‘FirstName’: ‘Monty’, ‘LastName’:'Python’)

mydiction.update(abc)


print mydiction

This will combine the two dictionaries and result in the printout:

  John Cleese Monty Python

{mospagebreak title=Operators}

The following is a list of operators you can use in Python:

 

Symbol

Type

What it Does

+

Mathematical

Addition

-

Mathematical

Subtraction

*

Mathematical

Multiplication

/

Mathematical

Division

//

Mathematical

Truncating Division

**

Mathematical

Powers

%

Modulos

Returns the remainder from a division

<<

Shift

Left Shift

>>

Shift

Right Shift

&

Logical

And

|

Logical

Or

^

Logical

Bitwise XOR

~

Logical

Bitwise Negation

<

Comparison

Less than

>

Comparison

Greater than

‘==’

Comparison

Equal to

!=

Comparison

Not Equal To

>=

Comparison

Greater than or Equal To

<=

Comparison

Less than or Equal To

‘=’

Assignment

Assigns a value

+=

Assignment

Adds and assigns a value

-=

Assignment

Subtracts and Assigns a value

*=

Assignment

Multiplies and assigns a value

/=

Assignment

Divides and assigns a value

//=

Assignment

Truncate Divides and assigns a value

**=

Assignment

Powers and assigns

%=

Assignment

Modulus and assigns

>>

Assignment

Shifts and assigns

<<

Assignment

Shifts and assigns

And

Boolean


Or

Boolean


Not

Boolean


Unfortunately I don’t have time to discuss these operators in this tutorial, but join me for the next episode where I will be discussing Sets and how to manipulate data with the rest of these operators. Thanks again for stopping by and remember to check in often for new series from yours truly and others.

Till then…

Google+ Comments

Google+ Comments