CSCE 110 — Programming IBasics of Python: Lists, Tuples, and FunctionsDr. Tiffani L. WilliamsDepartment of Computer Science and EngineeringTexas A&M UniversityFall 2011ListsIOrdered collection of data.IExample: some_data = [“dog”, 78, 87.0, “gorilla”]IElements can be of different types (heterogeneous)ICan have a mixture of strings, ints, floats, lists, etc.IComposed of elements that can be accessed by indexingICan create sublists by specifying an index rangeIThis is accomplished with the slicing operator [:] or [::]IYou can change individual elements directly (“mutable”)IUnlike strings, each element in a list can be modifiedIList creation operator [ ] , elements of the list are separated bycommasList: Examples>>> aList = [1, 2, 3, 4] # list creation>>> aList[1, 2, 3, 4]>>> aList[0] # indexing individual elements1>>> aList[2:] # creating sublist[3, 4]>>> aList[:3] # creating sublist[1, 2, 3]>>> aList[1] = 5 # mutable>>> aList[1, 5, 3, 4]TuplesITuples are similar to lists except for one important difference.Unlike lists, tuples are immutable.IExample: some_data = (“dog”, 78, 87.1, “gorilla”)IAn element in a tuple cannot be changed. In that sense, bothstrings and tuples share the immutability criterion.IReason for immutability: you don’t want variable’s contents tobe accidentally overwritten.ITuple creation operator ( ) , elements of the list are separatedby commasTuple: Examples>>> aTuple = (’robots’, 77, 93, ’try’) # tuple creation>>> aTuple(’robots’, 77, 93, ’try’)>>> aTuple[:3] # creating subtuples(’robots’, 77, 93)>>> aTuple[1] = 5 # immutableTraceback (most recent call last):File "<string>", line 1, in <fragment>TypeError: ’tuple’ object does not support item assignmentfor Loopfor iter_var in iterable:suite_to_repeatObjects that are iterable include strings, lists, and tuples.for loop: ExamplesListing 1: for-example.pyfor each l etter in " N ame s ":pr int " c u rren t l ett er :" , e achl e t ter Listing 2: for-example2.pynam e _lis t = [ ’ Walt er ’ , " Nic o le " , ’ Ste ven ’ ] # i tera t ing ov er a lis tfor each _ name in n a me_l i st :pr int e ach _na me , " Smi th " while vs for loopsListing 3: while-vs-for.py# Sho ws the diff e rence bet ween wh ile and for l oop s by# p rint ing t he n umbe rs fro m 1 to 5.pr int " w hil e loo p : P rint ing the num b ers f rom 1 to 5. "i = 1wh ile i < 6: # could a lso w rit e whil e i <= 5:pr int ii += 1pr int "\ n for loo p : P rint ing the num b ers f rom 1 to 5. "for i in range (1 ,6): # r ang e (1 ,6) cre ates t he l ist [1 , 2 , 3 , 4, 5]pr int i Concatenating Lists or Tuples: Examples>>> aList = [1, 2, 3] # list creation>>> aList + [4, 5] # list concatenation[1, 2, 3, 4, 5]>>> aTuple = (’four’, ’five’) # tuple creation>>> aTuple + (’six’) # immutableTraceback (most recent call last):File "<string>", line 1, in <fragment>TypeError: can only concatenate tuple (not "str") to tuple>>> aList # print aList[1, 2, 3]>>> aTuple # print aTuple(’four’, ’five’)>>> aList + [aTuple] # concatenate list and tuple as a list[1, 2, 3, (’four’, ’five’)]>>> aList + aTuple # immutableTraceback (most recent call last):File "<string>", line 1, in <fragment>TypeError: can only concatenate list (not "tuple") to listDefining a FunctionIA function is a named block of statements that performs anoperation.ITo define a function, we use the following syntax:def func(param_list):blockIWhen executed, this compound statement creates a newfunction object and assigns it to the name func.Ifunc is a valid Python name (think of valid variable names),param_list represents zero or more comma-separatedparameters, and block is an indented block of statements.Function Examples (1)Listing 4: function-example.py# A sim ple exa mple of how to us e func t ionsdef prin t _msg ():pr int "I love Pyt hon ! "def ise ven ( num ):pr int num % 2 == 0pri n t_ms g ()ise ven (1 0)ise ven (7) Function Examples (2)Listing 5: temperature-converter.py# C onve rts t he t e mpera t u re to Cels ius or F a hren h e itdef to_fa h r enhei t ( c ): # Con vert ce l sius to f ahren h eitret urn ( c * 9.0/ 5 .0) + 32def to_c e lsius ( f ): # Con vert fah r enhei t to c els i usret urn ( f - 32) * 5 .0/9 .0ty pe = r aw_i n put ( " C onve rt t emper a ture to C elsi us or F ahre n h eit ( c or f )? " )if type == ’c ’:tem p e ratu r e = in t ( r a w_in p ut (" E nte r F a hrenh e it t emper a ture : " ))cel sius = t o _cel s i us ( t e m pera t u re )pr int "%d F ahre n h eit is % d Cels ius . " % ( temp era ture , cels i us )el se :tem p e ratu r e = in t ( r a w_in p ut (" E nte r C elsi us t e mper a t ure : " ))fah r enhei t = t o _fahr e n heit ( t e mpera t ure )pr int "%d Cels ius is % d F ahre n heit . " % ( temp era ture , f ahre n h eit ) Function Examples (3)Listing 6: temperature-converter2.py# C onve rts t he t e mpera t u re to Cels ius or F a hren h e itdef to_fa h r enhei t ( c ): # Con vert ce l sius to f ahren h eitret urn ( c * 9.0/ 5 .0) + 32def to_c e lsius ( f ): # Con vert fah r enhei t to c els i usret urn ( f - 32) * 5 .0/9 .0def ma in () :ty pe = r aw_i n put ( " C onve rt t emper a ture to C elsi us or F ahre n h eit ( c or f )? " )if type == ’c ’:tem p e ratu r e = in t ( r a w_in p ut (" E nte r F a hrenh e it t emper a ture : " ))cel sius = t o _cel s i us ( t e m pera t u re )pr int "%d F ahre n h eit is % d Cels ius . " % ( temp era ture , cels i us )el se :tem p e ratu r e = in t ( r a w_in p ut (" E nte r C elsi us t e mper a t ure : " ))fah r enhei t = t o _fahr e n heit ( t e mpera t ure )pr int "%d Cels ius is % d F ahre n heit . " % ( temp era ture , f ahre n h eit )# E xecu t ion of the p rogr am …
View Full Document