[Tutor] Strings

Peter Otten __peter__ at web.de
Wed Nov 5 19:11:58 CET 2014


William Becerra wrote:

> Hey, I'm new to programming
> running Python 2.7.8 Windows 8.1
> I was reading 'How to Think Like a Computer Scientist- Learning with
> Python' chapter 7 sub-chapter 7.7
> 
> I have the following code:
> names = "John, Cindy, Peter"
> def find(str, ch, s):
>     index = 0
>     while index < len(str):
>         if s==1:
>             for char in names[:4]:
>                 if str[index] == ch:
>                     return index + 1
>                 index = index + 1
>         if s==2:
>             for char in names[6:11]:
>                 if str[index] == ch:
>                     return index + 1
>                 index = index + 1
>         if s==3:
>             for char in names[13:]:
>                 if str[index] == ch:
>                     return index + 1
>                 index = index + 1
>     return -1
> print find(names,"n", 2)
> 
> 
> 
> and my problem is:
> I intend for the parameter s to tell the interpreter which name to look at
> so that i get the index return value related to that name.
> for example:
> John and Cindy both have a letter 'n' but when I call the function
> with an s value of 2 I want it to return the index value of the letter n
> in Cindy and not in John.
> 
> Can Someone Please tell me why my code isn't working like I intend it to?
> Thank you

While Python has ready-to-use solutions for the subproblems of what you are 
trying to do, solving the problem by hand is still a good learning 
experience. But you are trying to do too much at the same time.

Can you write a function that finds a char in one name?
Once you have that -- let's call it find_char() -- you can rewrite your 
find() as

def find(names, ch, name_index):
    if name_index == 1:
        name = names[:4]
    elif name_index == 2:
        name = names[6:11]
    elif name_index == 3:
        name = names[13:]
    else:
        # if you know about exceptions raise a ValueError instead
        # of printing the error message
        print "ERROR: name_index must be 1, 2, or 3" 
        return None
    return find_char(name, ch)




More information about the Tutor mailing list