Find and counter

Find:

                       

In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.

This pattern of computation – traversing a sequence and returning when we find what we are looking for – is called a search.

 

Looping and counting

The following program counts the number of times the letter a appears in a string:

 

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result – the total number of a’s.

 

from Thinking in Python

posted @ 2014-06-23 22:06  平静缓和用胸音说爱  阅读(232)  评论(0编辑  收藏  举报