Thursday, October 9, 2008

Chapter 3 Continued

Since it won't let me go into Joseph's old posts, I am creating an entirely new one with related data.

This post goes into more detail with some of the things Joe touched on in his previous post for Chapter 3. In creating variables, there are a few certain words that you can’t use because Python has them saved for special functions. These words are: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, or yield. You also can not start your variable with a number or a non-alphabetical character such as a dollar sign, a pound sign, an asterisk, etc. You can, however, use the underscore character.

Other information types, aside from numbers and strings, which are built into Python are tuples, lists, and dictionaries. Tuples are sequences of values that are individually accessible. Tuples are used when you want to assign values to match more than one format specifier in a string. They are created by using normal parenthesis.

A list is similar to a tuple. Lists are created using square brackets. Other than the brackets, the main difference between a list and a tuple is that a list can be changed after it has been created. To add one item to the end of a list, you use the append method. For example if you had a list named vehicles, you would add a jet ski to the list by coding the following:
vehicle.append(“jet ski”)

If you want to add more than one item to the end of a list, you must use the extend method. For example:
Vehicle.extend(“jet ski”, “moped”, “train”)

There is another way to grow a list. That is through appending a sequence. If you had a list that you wanted to combine with another list, you can just add it at the end. Say you took your vehicle list and wanted to add a list of brand names to it. It can be done as follows:

vehicle = []
vehicle.extend(brand_name)
vehicle
[‘jet ski’, ‘moped’, ‘train’, ‘Kawasaki’, ‘Sea Doo’]

A third type of class is dictionaries. They are similar to tuples and lists. The difference between dictionaries and tuples & lists is that data is stored by names that you choose rather than their numeric order. Ex:

movie_choices = {}
movie.choices[“action”] = “Terminator 2”
movie.choices[“comedy”] = “Superbad”
movie.choices[“drama”] = “The Count of Monte Cristo”

Another way to create a dictionary while assigning keys (the words within the square brackets) and values (what comes after the equals sign) is as follows:

movie.choices = {“action” : “Terminator 2” , “comedy” : “Superbad” , “drama” : “The Count of Monte Cristo”

To find out what the keys of a dictionary are, you have to type the following:

movie_choices.keys()
[‘action’, ‘comedy’, ‘drama’]

The same thing works for finding the values:

Movie_choices.values( )
[‘Terminator 2’ , ‘Superbad’ , ‘The Count of Monte Cristo’]

No comments: