Learning python - part 1 - chapter 3

39
Learning Python Part 1 | Winter 2014 | Koosha Zarei | QIAU

description

Learning python series based on "Beginning Python Using Python 2.6 and P - James Payne" book presented by Koosha Zarei.

Transcript of Learning python - part 1 - chapter 3

Page 1: Learning python - part 1 - chapter 3

Learning PythonPart 1 | Winter 2014 | Koosha Zarei | QIAU

Page 2: Learning python - part 1 - chapter 3

Part 1Chapter 3 – Variables — Names for Values

Page 3: Learning python - part 1 - chapter 3

3February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Assigning Values to NamesMultiple AssignmentNames We Can’t UseUsing More Built - in TypesTuples-Unchanging Sequences of DataListDictionaryTreating a String Like a ListSpecial Types

Content

Page 4: Learning python - part 1 - chapter 3

4February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Assigning Values to NamesVariables are nothing but reserved memory locations to store values.Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

Page 5: Learning python - part 1 - chapter 3

5February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Assigning Values to NamesThe operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

>>> 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))The first variables are This is a string, This is another string, 4, 5

Page 6: Learning python - part 1 - chapter 3

6February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Assigning Values to NamesChanging data through names

>>> proverb = “A penny saved”>>> proverb = proverb + “ is a penny earned”>>> print(proverb)A penny saved is a penny earned>>> pennies_saved = 0>>> pennies_saved = pennies_saved + 1>>> print(pennies_saved)1print(pennies_saved + 1)2

counter = 100 # An integer assignmentmiles = 1000.0 # A floating pointname = "John" # A string

print counterprint milesprint name

Page 7: Learning python - part 1 - chapter 3

7February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Assigning Values to NamesCopying data

>>> pennies_saved=1>>> pennies_earned = pennies_saved>>> print(pennies_earned)1

Page 8: Learning python - part 1 - chapter 3

8February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Multiple AssignmentPython allows you to assign a single value to several variables simultaneously.

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location

a = b = c = 1

Page 9: Learning python - part 1 - chapter 3

9February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Multiple AssignmentPython allows you to assign a single value to several variables simultaneously.

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location

a = b = c = 1

Page 10: Learning python - part 1 - chapter 3

10February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Multiple AssignmentAassign multiple objects to multiple variables.

Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c

a, b, c = 1, 2, "john"

Page 11: Learning python - part 1 - chapter 3

11February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Names We Can’t UsePython uses a few names as special built-in words that it reserves for special use. These words are reserved by Python and can’t be used as the names for data.

and, as, assert, break, class, continue, def, del, elif, else, except, exec,False, finally, for, from, global, if, import, in, is, lambda, not, None, or, pass, print, raise, return, try, True, while, with, yield.

Page 12: Learning python - part 1 - chapter 3

12February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Using More Built - in TypesPython provides four other important basic types: tuples, lists, sets, and dictionaries.They all allow you to group more than one item of data together under one name. We have capability to search.

When you write a program, or read someone else’s program, it is important to pay attention to the type of enclosing braces when you see groupings of elements. The differences among {}, [], and () are important.

Page 13: Learning python - part 1 - chapter 3

13February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Tuples are a sequence of values, each one accessible individually, and a tuple is a basic type in Python.Tuples are immutable and tuples use parentheses and.We can recognize tuples when they are created because they’re surrounded by parentheses:

tup1 = ('physics', 'chemistry', 1997, 2000);tup2 = (1, 2, 3, 4, 5 );tup3 = "a", "b", "c", "d";

Page 14: Learning python - part 1 - chapter 3

14February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

>>> filler = (“string”, “filled”, “by a”, “tuple”)>>> print(filler)(‘string’, ‘filled’, ‘by a ‘, ‘tuple’)

>>> print(“A %s %s %s %s” % (“string”, “filled”, “by a”, “tuple”))A string filled by a tuple

Page 15: Learning python - part 1 - chapter 3

15February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Accessing Values in TuplesTo access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. (dereference feature of the language)

tup1 = ('physics', 'chemistry', 1997, 2000);tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0]print "tup2[1:5]: ", tup2[1:5]

Page 16: Learning python - part 1 - chapter 3

16February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Updating TuplesTuples are immutable which means you cannot update them or change values of tuple elements. But we able to take portions of an existing tuples to create a new tuples as follows.

tup1 = (12, 34.56);tup2 = ('abc', 'xyz');

# Following action is not valid for tuples# tup1[0] = 100;

# So let's create a new tuple as followstup3 = tup1 + tup2;print tup3;

Page 17: Learning python - part 1 - chapter 3

17February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Delete Tuple ElementsRemoving individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.

tup = ('physics', 'chemistry', 1997, 2000);

print tup;del tup;print "After deleting tup : "print tup;

Page 18: Learning python - part 1 - chapter 3

18February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Basic Tuples Operations:Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.

>>>len((1, 2, 3))>>>(1, 2, 3) + (4, 5, 6)>>>['Hi!'] * 4>>>3 in (1, 2, 3)>>>for x in (1, 2, 3): print x,

Page 19: Learning python - part 1 - chapter 3

19February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Indexing, Slicing, and MatrixesBecause tuples are sequences, indexing and slicing work the same way for tuples as they do for strings.

L = ('spam', 'Spam', 'SPAM!')

>>>L[2]'SPAM!' Offsets start at zero>>>L[-2]'Spam' Negative: count from the right>>>L[1:]['Spam', 'SPAM!'] Slicing fetches sections

Page 20: Learning python - part 1 - chapter 3

20February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Built-in Tuple FunctionsPython includes the following tuple functions:

1. cmp(tuple1, tuple2) # Compares elements of both tuples.2. len(tuple) # Gives the total length of the tuple.3. max(tuple) # Returns item from the tuple with max value.4. min(tuple) # Returns item from the tuple with min value.5. tuple(seq) # Converts a list into tuple.

Page 21: Learning python - part 1 - chapter 3

21February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Indexing, Slicing, and MatrixesBecause tuples are sequences, indexing and slicing work the same way for tuples as they do for strings.

L = ('spam', 'Spam', 'SPAM!')

>>>L[2]'SPAM!' Offsets start at zero>>>L[-2]'Spam' Negative: count from the right>>>L[1:]['Spam', 'SPAM!'] Slicing fetches sections

Page 22: Learning python - part 1 - chapter 3

22February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Tuples — Unchanging Sequences of Data

Multidimensional

>>> a = (“first”, “second”, “third”)>>> b = (a, “b’s second element”)>>> print(“%s” %b[1])b’s second element>>> print(“%s” % b[0][0])first>>> print(“%s” % b[0][1])second>>> print(“%s” % b[0][2])third

Page 23: Learning python - part 1 - chapter 3

23February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

ListLists, like tuples, are sequences that contain elements referenced starting at zero. Lists are created by using square brackets.Like tuples, the elements in a list are referenced starting at 0 and are accessed in the same order from 0 until the end.

>>> breakfast = [ “coffee”, “tea”, “toast”, “egg” ]

Page 24: Learning python - part 1 - chapter 3

24February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

List

>>> count = 0>>> print(“Today’s breakfast is %s” % breakfast[count])Today’s breakfast is coffee>>> count = 1>>> print(“Today’s breakfast is %s” % breakfast[count])Today’s breakfast is tea>>> count = 2>>> print(“Today’s breakfast is %s” % breakfast[count])Today’s breakfast is toast>>> count = 3>>> print(“Today’s breakfast is %s” % breakfast[count])Today’s breakfast is egg

Page 25: Learning python - part 1 - chapter 3

25February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

ListThe primary difference in using a list versus using a tuple is that a list can be modified after it has been created.

>>> breakfast[count] = “sausages”>>> print(“Today’s breakfast is %s” % breakfast[count])Today’s breakfast is sausages

Page 26: Learning python - part 1 - chapter 3

26February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

ListMore feature...

>>> breakfast.append(“waffles”)>>> count = 4>>> print (“Today’s breakfast is %s” % breakfast[count])Today’s breakfast is waffles

>>> breakfast.extend([“juice”, “decaf”, “oatmeal”])>>> print(breakfast)[‘coffee’, ‘tea’, ‘toast’, ‘egg’, ‘waffle’, ‘juice’, ‘decaf’, ‘oatmeal’]

>>> del breakfast[2]>>> print(breakfast)[‘coffee’, ‘tea’, ‘egg’, ‘waffle’, ‘juice’, ‘decaf’, ‘oatmeal’]

Page 27: Learning python - part 1 - chapter 3

27February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

ListBuilt-in List Functions & Methods:

Functions1 cmp(list1, list2) Compares elements of both lists.2 len(list) Gives the total length of the list.3 max(list) Returns item from the list with max value.4 min(list) Returns item from the list with min value.5 list(seq) Converts a tuple into list.

1 list.append(obj) Appends object obj to list2 list.count(obj) Returns count of how many times obj occurs in list3 list.extend(seq) Appends the contents of seq to list4 list.index(obj) Returns the lowest index in list that obj appears5 list.insert(index, obj) Inserts object obj into list at offset index6 list.pop(obj=list[-1]) Removes and returns last object or obj from list7 list.remove(obj) Removes object obj from list8 list.reverse() Reverses objects of list in place9 list.sort([func]) Sorts objects of list, use compare func if given

Page 28: Learning python - part 1 - chapter 3

28February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

DictionaryA dictionary is mutable and is another container type that can store any number of Python objects, including other container types.Dictionaries consist of pairs (called items) of keys and their corresponding values.Dictionaries are created using the curly braces.

Page 29: Learning python - part 1 - chapter 3

29February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Dictionary

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

dict1 = { 'abc': 456 };dict2 = { 'abc': 123, 98.6: 37 };

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Page 30: Learning python - part 1 - chapter 3

30February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Dictionary

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

>>> print "dict['Name']: ", dict['Name'];>>> print "dict['Age']: ", dict['Age'];

dict['Name']: Zaradict['Age']: 7

Accessing Values in Dictionary

Page 31: Learning python - part 1 - chapter 3

31February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Dictionary

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

>>> dict['Age'] = 8; # update existing entry>>> dict['School'] = "DPS School"; # Add new entry

>>> print "dict['Age']: ", dict['Age'];>>> print "dict['School']: ", dict['School'];

dict['Age']: 8dict['School']: DPS School

Updating Dictionary

Page 32: Learning python - part 1 - chapter 3

32February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Dictionary

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

>>> del dict['Name']; # remove entry with key 'Name'>>> dict.clear(); # remove all entries in dict>>> del dict ; # delete entire dictionary

>>> print "dict['Age']: ", dict['Age'];>>> print "dict['School']: ", dict['School'];

dict['Age']:Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age'];TypeError: 'type' object is unsubscriptable

Delete Dictionary Elements

Page 33: Learning python - part 1 - chapter 3

33February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Dictionary

Funcion:1 cmp(dict1, dict2) Compares elements of both dict.2 len(dict) Gives the total length of the dictionary. This would

be equal to the number of items in the dictionary.3 str(dict) Produces a printable string representation of a

dictionary4 type(variable) Returns the type of the passed variable. If passed

variable is dictionary, then it would return a dictionary type.

Built-in Dictionary Functions & Methods

Page 34: Learning python - part 1 - chapter 3

34February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Dictionary

1 dict.clear() Removes all elements of dictionary dict2 dict.copy() Returns a shallow copy of dictionary dict3 dict.fromkeys() Create a new dictionary with keys from seq and values set to value.4 dict.get(key, default=None) For key key, returns value or default if key not in dictionary5 dict.has_key(key) Returns true if key in dictionary dict, false otherwise6 dict.items() Returns a list of dict's (key, value) tuple pairs7 dict.keys() Returns list of dictionary dict's keys8 dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is

not already in dict9 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict10 dict.values() Returns list of dictionary dict's values

Built-in Dictionary Functions & Methods

Page 35: Learning python - part 1 - chapter 3

35February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Treating a String Like a ListPython offers an interesting feature of strings.

>>> last_names = [ “Douglass”, “Jefferson”, “Williams”, “Frank”, “Thomas” ]>>> print(“%s” % last_names[0])Douglass>>> print(“%s” % last_names[0][0])D>>> print(“%s” % last_names[1])Jefferson>>> print(“%s” % last_names[1][0])J>>> print(“%s” % last_names[2])Williams>>> print(“%s” % last_names[2][0])W>>> print(“%s” % last_names[3])Frank

Page 36: Learning python - part 1 - chapter 3

36February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Treating a String Like a ListRemember that, like tuples, strings are immutable. When you are slicing strings, you are actually creating new strings that are copies of sections of the original string.

Page 37: Learning python - part 1 - chapter 3

37February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Special TypesPython has a handful of special types:

None, True, FalseNone is special because there is only one None.True and False are special representations of the numbers 1 and 0.

>>> TrueTrue>>> FalseFalse>>> True == 1True>>> True == 0False

>>> False == 1False>>> False == 0True>>> False > 0False>>>False < 1True

Page 38: Learning python - part 1 - chapter 3

38February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Exercises1. Create a list called dairy_section with four elements from the dairy section of a supermarket.

2. Print a string with the first and last elements of the dairy_section list.

3. Create a tuple called milk_expiration with three elements: the month, day, and year of the expiration date on the nearest carton of milk.

4. Print the values in the milk_expiration tuple in a string that reads “This milk carton will

expire on 12/10/2009.”

5. 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:

❑expiration_date: Set it to the milk_expiration tuple.

❑ fl_oz: Set it to the size of the milk carton on which you are basing this.

❑ Cost: Set this to the cost of the carton of milk.

❑ brand_name: Set this to the name of the brand of milk you’re using.

6. 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.

Page 39: Learning python - part 1 - chapter 3

39February 2014Learning Python | Part 1- Chapter 3 | Koosha Zarei

Exercises7. Show how to calculate the cost of six cartons of milk based on the cost of milk_carton.8. 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.9. How do you count the number of cheeses in the cheese list?10. Print out the first five letters of the name of your first cheese.