12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

8.7. Looping and counting 75This is the first example we have seen of a return statement inside a loop. If word[index] ==letter,thefunction breaks out of theloop and returns immediately.Ifthecharacter doesn’t appear inthe string,theprogram exits theloop normally and returns-1.Thispatternofcomputation—traversingasequenceandreturningwhenwefindwhatwearelookingfor—iscalled asearch.Exercise 8.4 Modify find so that it has a third parameter, the index in word where it should startlooking.8.7 Looping and countingThe following program counts the number of timesthe letteraappears inastring:word = 'banana'count = 0for letter in word:if letter == 'a':count = count + 1print countThis program demonstrates another pattern of computation called a counter. The variable count isinitialized to 0 and then incremented each time an a is found. When the loop exits, count containstheresult—thetotal number ofa’s.Exercise 8.5 Encapsulate this code in a function named count, and generalize it so that it acceptsthestringand theletter as arguments.Exercise8.6 Rewritethisfunctionsothatinsteadoftraversingthestring,itusesthethree-parameterversion offindfromthe previous section.8.8 stringmethodsA method is similar to a function—it takes arguments and returns a value—but the syntax is different.For example, the method upper takes a string and returns a new string with all uppercaseletters:Instead ofthe function syntaxupper(word),ituses themethod syntaxword.upper().>>> word = 'banana'>>> new_word = word.upper()>>> print new_wordBANANAThis form of dot notation specifies the name of the method, upper, and the name of the string toapply the method to,word. The empty parentheses indicate that this method takes noargument.Amethodcalliscalledaninvocation;inthiscase,wewouldsaythatweareinvokingupperontheword.As it turns out, there is a string method named find that is remarkably similar to the function wewrote:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!