For the below code I get the required answer 15 for "Helix" string but also get this error: Your function crashed on xenophobia as input because your function throws a "string index out of range" error. why is this error coming? I tried debugging by printing at every stage but didn't understand my mistake. Also is this an effective way to code? where did I go wrong?

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}
def scrabble_score(word):
    total = 0
    length = len(word)
    for char in word:#to loop through the string
        for key in score:#to browse through the dictionary
            if key==word[length-1]:#compare string char with dict key  
                total = total + score[key]
                length = length -1
            if length==0:#to break the loop once string length is = to zero
    return total
print scrabble_score("helix")



if key==word[length-1]

why simply not use char? It contains the current character of word thanks to your first loop, it prevents index errors

Personally, once you have a character of word you can just that character as key to get the value from the dictionary using square brackets, even easier


Thanks I used char and the code worked. So you mean I need not require a second for loop to browse through the dictionary??

I actually got my code down to this!

def scrabble_score(word):
    word = word.lower()
    total = 0
    length = len(word)
    for char in word:
        total = total + score[char]
    return total
print scrabble_score("helix")

Thank You stetim 94!


well, as you have seen, the second loop is not needed

What you currently did is better then using a second loop :slight_smile:

this line:

length = len(word)

has become reduntant, you can remove it

For the rest, well done :slight_smile:


Thanks a Lot:grinning: