Python Programming - Chapter 3

  • View
    1.947

  • Download
    5

Embed Size (px)

DESCRIPTION

This is the 3rd lecture in a series of lectures for students learning Python programming

Text of Python Programming - Chapter 3

  • 1. Chapter 3 Variables Names for Values

2.

  • In most programs, you want to be able to store values for later use and not keep entering them time and time again
  • this is done with variables which is a way for you to tellthe computer that every time you mention the name forthe value, it will go into memory and retrieve theappropriate value
  • keep in mind that the computer does not really recognizenames but rather keep a table of memory addresses andthe name given to that address by the programmer (a wayto translate a name into its own language)
  • In Python, it is very easy to create variables
  • all you need to do is place the name of the variable on theleft side of an equality statement and from that point on(unless the value is altered later), that value will beassociated with the name

3.

  • Try this:
  • >>> first_string = "This is a string"
  • >>> second_string = "This is another string"
  • >>> first_number = 4
  • >>> second_number = 5
  • >>> print "The first variables are %s, %s, %d, %d" % (first_string,second_string, first_number, second_number)
  • Note: the variable name is all one word and is on the left side of the equals sign
  • it is VERY important to give your variable a name whichexplains what value it will contain (see above)
  • Variables can contain values that are apt to change and that is the true meaning of the word variable

4.

  • Try this:
  • >>> proverb = "A penny saved"
  • >>> proverb = proverb + " is a penny earned"
  • >>> print proverb
  • >>> pennies_saved = 0
  • >>> pennies_saved = pennies_saved + 1
  • >>> pennies_saved
  • Notice that a) the variable is always on the left side of the equals, and b) the variable may be on both sides of the equals if a value is being added to whatever is currently in the variable
  • In order to make variable names self-explanatory, you can put two or more words together by separating them with underscores or sometimes by capitalizing the first letter of the second word and so forth

5.

  • There are some words that are reserved in certain programming languages (and Python is not an exception)
  • these words carry special meaning and may not be usedfor regular variable names without damaging effects
  • In Python, the following words are reserved:
  • 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, yield
  • The only other restriction for variable names is that they not begin with numbers or most non-alphabetic characters, with the exception of the underscore character
  • Besides strings and numeric data types, Python has other built-in types such astuples, listsanddictionaries

6.

  • Tuples, list , anddictionariesallow you to group more than one item of data together under a single name, making it easier to store large amounts of data
  • The computer knows which data type you will be using by the way you create the variable
  • tuplesplace all its data inside a pair of ( )
  • listsplace all its data inside a pair of [ ]
  • dictionariesmust be declared first as an empty dictionarywith a pair of { } and only then can you start placingdata into the dictionary
  • All these data types act slightly differently and you must decide which one you will be needing for your program

7.

  • Tuplesare used when you want to assign values to match more than one format specifier in a string
  • they contain references to data such as strings andnumbers
  • Try this:
  • >>> filler = ("string", "filled", "by a", "tuple")
  • >>> print "A %s %s %s %s" % filler
  • You can also access a single value inside of atupleby placing square brackets after the name of thetuple
  • Be careful!Python, like most other languages, startscounting at zero and will always be one off of what youwould normally think about the location of the element

8.

  • If youre not too sure how many elements atuplehas, you can always use the function len to tell you how many items there are
  • for example:>>> len(filler)
  • will return the value 4, but the indeces into the elementsof filler will range from 0 to 3
  • Be aware that elements of atuplecan be anothertupleand that makes it multidimensional
  • in order to access an element of atuplewhich is in itselfanothertuple , you need to add another pair of squarebrackets

9.

  • Try this:
  • >>> a = ("first", "second", "third")
  • >>> b = (a, "b's second element")
  • >>> print "%s" % b[1]
  • >>> print "%s" % b[0][0]
  • >>> print "%s" % b[0][1]
  • >>> print "%s" % b[0][2]
  • Although there isnt a limit on the number of dimensions atuplecan have, after a while the number of dimensions will confuse the programmer so no more than three dimensions are recommended
  • The only oddity withtuplesis that if there is only one element in atuple , it needs to be followed with a , before closing the parentheses

10.

  • The biggest draw back to atupleis that once it is created, it cannot be changed
  • this is called immutability and this is true for stringsand most other languages have this same drawback
  • Lists , on the other hand, are changeable sequences of data
  • Listscontain its elements in a pair of square brackets and its elements are accessed the same way as withtuples

11.

  • Try this:
  • >>> count = 0
  • >>> breakfast = ["coffee", "tea", "toast", "egg"]
  • >>> print "Today's breakfast is %s" % breakfast[count]
  • >>> count = 1
  • >>> print "Today's breakfast is %s" % breakfast[count]
  • >>> print "Today's breakfast is %s" % breakfast[count]
  • >>> count = 2
  • >>> print "Today's breakfast is %s" % breakfast[count]
  • >>> count = 3
  • >>> print "Today's breakfast is %s" % breakfast[count]
  • Remember that the contents of alistcan be changed at any time and have no restrictions on them

12.

  • You can not only change the values that are stored in thelist , but you can add information to the end of thelist
  • the appendmethod allows you to add one item to theend of alist
  • for example: breakfast.append(waffle)
  • theextendmethod allows you to add more than item, oritems in atupleto the end of alist
  • for example: breakfast.extend([juice, oatmeal])
  • The length of alistcan also be accessed through thelenfunction, the same ways as with atuple

13.

  • Dictionariesare different fromtuplesandlistsmainly because they are accessed with names as opposed to numeric indeces
  • In addition,dictionariesneed to be declared before you start to add information in them and this is done with an empty pair of curly brackets
  • Individual items of adictionaryare added one at a time by placing the string index in a pair of square brackets and then the value associated with that index on the right side of an equals sign
  • This is perhaps the biggest drawback to using adictionary the creation of adictionaryis a two-step process

14.

  • Try this:
  • >>> menus_special = {}
  • >>> menus_special["breakfast"] = "canadian ham"
  • >>> menus_special["lunch"] = "tuna surprise"
  • >>> menus_special["dinner"] = "Cheeseburger deluxe
  • The name given to the indeces of adictionaryare called keys and the data are called values
  • You can see what information is stored in adictionaryby placing it on a line by itself in the shell and it will display the key followed by a colon and the associated value for every item
  • Try this:
  • >>> menus_special
  • {'lunch': 'tuna surprise', 'breakfast': 'canadian ham', 'dinner':'Cheeseburger deluxe'}

15.

  • The other difference withdictionariesis that you can access the individual elements by placing a string (instead of a number) inside the square brackets
  • Try this:
  • >>> print "%s" % menus_special["breakfast"]
  • >>> print "%s" % menus_special["lunch"]
  • >>> print "%s" % menus_special["dinner"]
  • If you want to know all the keys for yourdictionaryor all the values stored in the dictionary, you can used