Python Programming - Chapter 3

2,337 views

Published on

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

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,337
On SlideShare
0
From Embeds
0
Number of Embeds
25
Actions
Shares
0
Downloads
71
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Python Programming - Chapter 3

  1. 1. Chapter 3 Variables –Names for Values
  2. 2. <ul><li>In most programs, you want to be able to store values for later use and not keep entering them time and time again </li></ul><ul><li>this is done with variables which is a way for you to tell the computer that every time you mention the name for the value, it will go into memory and retrieve the appropriate value </li></ul><ul><li>keep in mind that the computer does not really recognize names but rather keep a table of memory addresses and the name given to that address by the programmer (a way to translate a name into its own language) </li></ul><ul><li>In Python, it is very easy to create variables </li></ul><ul><li>all you need to do is place the name of the variable on the left side of an equality statement and from that point on (unless the value is altered later), that value will be associated with the name </li></ul>
  3. 3. <ul><li>Try this: </li></ul><ul><li>>>> first_string = &quot;This is a string&quot; </li></ul><ul><li>>>> second_string = &quot;This is another string&quot; </li></ul><ul><li>>>> first_number = 4 </li></ul><ul><li>>>> second_number = 5 </li></ul><ul><li>>>> print &quot;The first variables are %s, %s, %d, %d&quot; % (first_string, second_string, first_number, second_number) </li></ul><ul><li>Note: the variable name is all one word and is on the left side of the equals sign </li></ul><ul><li>it is VERY important to give your variable a name which explains what value it will contain (see above) </li></ul><ul><li>Variables can contain values that are apt to change and that is the true meaning of the word “variable” </li></ul>
  4. 4. <ul><li>Try this: </li></ul><ul><li>>>> proverb = &quot;A penny saved&quot; </li></ul><ul><li>>>> proverb = proverb + &quot; is a penny earned&quot; </li></ul><ul><li>>>> print proverb </li></ul><ul><li>>>> pennies_saved = 0 </li></ul><ul><li>>>> pennies_saved = pennies_saved + 1 </li></ul><ul><li>>>> pennies_saved </li></ul><ul><li>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 </li></ul><ul><li>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 </li></ul>
  5. 5. <ul><li>There are some words that are “reserved” in certain programming languages (and Python is not an exception) </li></ul><ul><li>these words carry special meaning and may not be used for regular variable names without damaging effects </li></ul><ul><li>In Python, the following words are reserved: </li></ul><ul><li>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 </li></ul><ul><li>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 </li></ul><ul><li>Besides strings and numeric data types, Python has other built-in types such as tuples, lists and dictionaries </li></ul>
  6. 6. <ul><li>Tuples, list , and dictionaries allow you to group more than one item of data together under a single name, making it easier to store large amounts of data </li></ul><ul><li>The computer knows which data type you will be using by the way you create the variable </li></ul><ul><li>tuples place all its data inside a pair of “( )” </li></ul><ul><li>lists place all its data inside a pair of “[ ]” </li></ul><ul><li>dictionaries must be declared first as an empty dictionary with a pair of “{ }” and only then can you start placing data into the dictionary </li></ul><ul><li>All these data types act slightly differently and you must decide which one you will be needing for your program </li></ul>
  7. 7. <ul><li>Tuples are used when you want to assign values to match more than one format specifier in a string </li></ul><ul><li>they contain references to data such as strings and numbers </li></ul><ul><li>Try this: </li></ul><ul><li>>>> filler = (&quot;string&quot;, &quot;filled&quot;, &quot;by a&quot;, &quot;tuple&quot;) </li></ul><ul><li>>>> print &quot;A %s %s %s %s&quot; % filler </li></ul><ul><li>You can also access a single value inside of a tuple by placing square brackets after the name of the tuple </li></ul><ul><li>Be careful! Python, like most other languages, starts counting at zero and will always be one off of what you would normally think about the location of the element </li></ul>
  8. 8. <ul><li>If you’re not too sure how many elements a tuple has, you can always use the function “ len ” to tell you how many items there are </li></ul><ul><li>for example: >>> len(filler) </li></ul><ul><li>will return the value “4”, but the indeces into the elements of filler will range from 0 to 3 </li></ul><ul><li>Be aware that elements of a tuple can be another tuple and that makes it multidimensional </li></ul><ul><li>in order to access an element of a tuple which is in itself another tuple , you need to add another pair of square brackets </li></ul>
  9. 9. <ul><li>Try this: </li></ul><ul><li>>>> a = (&quot;first&quot;, &quot;second&quot;, &quot;third&quot;) </li></ul><ul><li>>>> b = (a, &quot;b's second element&quot;) </li></ul><ul><li>>>> print &quot;%s&quot; % b[1] </li></ul><ul><li>>>> print &quot;%s&quot; % b[0][0] </li></ul><ul><li>>>> print &quot;%s&quot; % b[0][1] </li></ul><ul><li>>>> print &quot;%s&quot; % b[0][2] </li></ul><ul><li>Although there isn’t a limit on the number of dimensions a tuple can have, after a while the number of dimensions will confuse the programmer so no more than three dimensions are recommended </li></ul><ul><li>The only oddity with tuples is that if there is only one element in a tuple , it needs to be followed with a “,” before closing the parentheses </li></ul>
  10. 10. <ul><li>The biggest draw back to a tuple is that once it is created, it cannot be changed </li></ul><ul><li>this is called “immutability” and this is true for strings and most other languages have this same drawback </li></ul><ul><li>Lists , on the other hand, are changeable sequences of data </li></ul><ul><li>Lists contain its elements in a pair of square brackets and its elements are accessed the same way as with tuples </li></ul>
  11. 11. <ul><li>Try this: </li></ul><ul><li>>>> count = 0 </li></ul><ul><li>>>> breakfast = [&quot;coffee&quot;, &quot;tea&quot;, &quot;toast&quot;, &quot;egg&quot;] </li></ul><ul><li>>>> print &quot;Today's breakfast is %s&quot; % breakfast[count] </li></ul><ul><li>>>> count = 1 </li></ul><ul><li>>>> print &quot;Today's breakfast is %s&quot; % breakfast[count] </li></ul><ul><li>>>> print &quot;Today's breakfast is %s&quot; % breakfast[count] </li></ul><ul><li>>>> count = 2 </li></ul><ul><li>>>> print &quot;Today's breakfast is %s&quot; % breakfast[count] </li></ul><ul><li>>>> count = 3 </li></ul><ul><li>>>> print &quot;Today's breakfast is %s&quot; % breakfast[count] </li></ul><ul><li>Remember that the contents of a list can be changed at any time and have no restrictions on them </li></ul>
  12. 12. <ul><li>You can not only change the values that are stored in the list , but you can add information to the end of the list </li></ul><ul><li>the “ append” method allows you to add one item to the end of a list </li></ul><ul><li>for example: breakfast.append(“waffle”) </li></ul><ul><li>the “extend” method allows you to add more than item, or items in a tuple to the end of a list </li></ul><ul><li> for example: breakfast.extend([“juice”, “oatmeal”]) </li></ul><ul><li>The length of a list can also be accessed through the “len” function, the same ways as with a tuple </li></ul>
  13. 13. <ul><li>Dictionaries are different from tuples and lists mainly because they are accessed with names as opposed to numeric indeces </li></ul><ul><li>In addition, dictionaries need to be declared before you start to add information in them and this is done with an empty pair of curly brackets </li></ul><ul><li>Individual items of a dictionary are 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 </li></ul><ul><li>This is perhaps the biggest drawback to using a dictionary – the creation of a dictionary is a two-step process </li></ul>
  14. 14. <ul><li>Try this: </li></ul><ul><li>>>> menus_special = {} </li></ul><ul><li>>>> menus_special[&quot;breakfast&quot;] = &quot;canadian ham&quot; </li></ul><ul><li>>>> menus_special[&quot;lunch&quot;] = &quot;tuna surprise&quot; </li></ul><ul><li>>>> menus_special[&quot;dinner&quot;] = &quot;Cheeseburger deluxe“ </li></ul><ul><li>The name given to the indeces of a dictionary are called “keys” and the data are called “values” </li></ul><ul><li>You can see what information is stored in a dictionary by 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 </li></ul><ul><li>Try this: </li></ul><ul><li>>>> menus_special </li></ul><ul><li>{'lunch': 'tuna surprise', 'breakfast': 'canadian ham', 'dinner': 'Cheeseburger deluxe'} </li></ul>
  15. 15. <ul><li>The other difference with dictionaries is that you can access the individual elements by placing a string (instead of a number) inside the square brackets </li></ul><ul><li>Try this: </li></ul><ul><li>>>> print &quot;%s&quot; % menus_special[&quot;breakfast&quot;] </li></ul><ul><li>>>> print &quot;%s&quot; % menus_special[&quot;lunch&quot;] </li></ul><ul><li>>>> print &quot;%s&quot; % menus_special[&quot;dinner&quot;] </li></ul><ul><li>If you want to know all the keys for your dictionary or all the values stored in the dictionary, you can used the built-in function keys() and values() </li></ul><ul><li>for example: menus_special.keys() -or- menus_special.values() </li></ul><ul><li>The return values can be stored into a list for use later on </li></ul>
  16. 16. <ul><li>Another feature of a dictionary is that you can find out whether you’ve already used a key </li></ul><ul><li>this is done with the has_key() function which will return a True or False value </li></ul><ul><li>Try this: </li></ul><ul><li>>>> menus_special.has_key(&quot;junk&quot;) </li></ul><ul><li>>>> menus_special.has_key(&quot;breakfast&quot;) </li></ul><ul><li>>>> menus_special.has_key(&quot;canadian ham&quot;) </li></ul><ul><li>True and False are built-in values which really represent 1 and 0, but is more intuitive to a programmer </li></ul><ul><li>Strings are interesting in that they can be treated as list of individual characters, but please remember that they are immutable </li></ul>
  17. 17. <ul><li>Certain elements of a string can be removed and this is a technique called “slicing” </li></ul><ul><li>these new slices are actually brand new strings that are being created, regardless of their new length </li></ul><ul><li>Additional Features of Python </li></ul><ul><li>Another special built-in value, besides True and False , is None </li></ul><ul><li>this is used with functions that have nothing to return to the calling program </li></ul><ul><li>Python allows you to access elements of a tuple , list or string from the end by placing a negative value in the square brackets </li></ul><ul><li>for example: [-1] will access the last elements, [-2] will access the next-to-last element, etc. </li></ul>
  18. 18. <ul><li>Another feature to remember is that whenever a slice is created from a list or a tuple , the result is another list or tuple , depending on what you sliced from </li></ul><ul><li>Try this: </li></ul><ul><li>>>> slice_this_tuple = (&quot;The&quot;, &quot;next&quot;, &quot;time&quot;, &quot;we&quot;, &quot;meet&quot;, &quot;drinks&quot;, &quot;are&quot;, &quot;on&quot;, &quot;me&quot;) </li></ul><ul><li>>>> sliced_tuple = slice_this_tuple[5:9] </li></ul><ul><li>>>> sliced_tuple </li></ul><ul><li>>>> slice_this_list = [&quot;The&quot;, &quot;next&quot;, &quot;time&quot;, &quot;we&quot;, &quot;meet&quot;, &quot;drinks&quot;, &quot;are&quot;, &quot;on&quot;, &quot;me&quot;] </li></ul><ul><li>>>> sliced_list = slice_this_list[5:9] </li></ul><ul><li>>>> sliced_list </li></ul><ul><li>>>> slice_this_string = &quot;The next time we meet, drinks are on me&quot; </li></ul><ul><li>>>> sliced_string = slice_this_string[5:9] </li></ul><ul><li>>>> sliced_string </li></ul>
  19. 19. <ul><li>Keep in mind that if you use a colon to specify which elements to slice from, a new sequence of that same type is created and contains just those elements </li></ul><ul><li>Another way to expand lists is by appending sequences, but be aware that a single elements of the list will now be a sequence by itself, thereby making it multidimensional </li></ul><ul><li>Lists can also have values deleted from them by using the “pop” function and you can even specify which element you want removed by placing it in the parentheses </li></ul>
  20. 20. <ul><li>Try this: </li></ul><ul><li>>>> todays_temperatures = [23, 32, 33, 31] </li></ul><ul><li>>>> todays_temperatures.append(29) </li></ul><ul><li>>>> todays_temperatures </li></ul><ul><li>>>> morning = todays_temperatures.pop(0) </li></ul><ul><li>>>> print &quot;This mornings temperature was %.02f&quot; % morning </li></ul><ul><li>>>> late_morning = todays_temperatures.pop(0) </li></ul><ul><li>>>> print &quot;Todays late morning temperature was %.02f&quot; % late_morning </li></ul><ul><li>>>> noon = todays_temperatures.pop(0) </li></ul><ul><li>>>> print &quot;Todays noon temperature was %.02f&quot; % noon </li></ul><ul><li>>>> todays_temperatures </li></ul><ul><li>Note: you can “pop” an element from a list and never use it (it will be automatically discarded from memory </li></ul>
  21. 21. Exercises <ul><li>Create a list called dairy_section with four elements from the dairy section of a supermarket. </li></ul><ul><li>Print a string with the first and last elements of the dairy_section list. </li></ul><ul><li>Create a tuple called milk-expiration with three elements: the month, day and year of the expiration date on the nearest carton of milk </li></ul>
  22. 22. <ul><li>Print the values in the milk_expiration tuple in a string that reads “This milk will expire on 12/10/2005”. </li></ul><ul><li>Create an empty dictionary called milk_carton. Add the following key/value pairs. You can make up the values or use a real milk carton: </li></ul><ul><ul><li>expiration_date : set it to the milk_expiration tuple </li></ul></ul><ul><ul><li>fl_oz : set it to the size of the milk carton on which you are basing this </li></ul></ul><ul><ul><li>cost : set this to the cost of a carton of milk </li></ul></ul><ul><ul><li>brand_name : set this to the brand name of milk you drink </li></ul></ul>
  23. 23. <ul><li>Print out the values of all of the elements of the milk_carton using the values in the dictionary , and not, for instance, using the data in the milk_expiration tuple </li></ul><ul><li>Show how to calculate the cost of six cartons of milk based on the cost of milk_carton. </li></ul><ul><li>Create a list called cheeses. List all of the cheeses you can think of. Append this list to the dairy_section list, and look at the contents of dairy_section. Then remove the list of cheeses from the array. </li></ul>
  24. 24. <ul><li>How do you count the number of cheeses in the cheese list? </li></ul><ul><li>Print out the first five letters of the name of your first cheese. </li></ul>

×