Section 9.18 Optional parameters
To find the locations of the second or third occurrence of a character in a string, we can modify the
findfunction, adding a third parameter for the starting position in the search string:
find2('banana', 'a', 2)now returns
3, the index of the first occurrence of ‘a' in ‘banana' after index 2. What does
find2('banana', 'n', 3)return? If you said, 4, there is a good chance you understand how
find2works. Try it.
Better still, we can combine
find2using an optional parameter.
find3('banana', 'a', 2)to this version of
findbehaves just like
find2, while in the call
startwill be set to the default value of
Adding another optional parameter to
findmakes it search from a starting position, up to but not including the end position.
The optional value for
endis interesting. We give it a default value
Noneif the caller does not supply any argument. In the body of the function we test what
endis and if the caller did not supply any argument, we reassign
endto be the length of the string. If the caller has supplied an argument for
end, however, the caller's value will be used in the loop.
The semantics of
endin this function are precisely the same as they are in the
You have attempted of activities on this page.