9/15 scrabble_score help (only returning value of first letter)


#1

Having trouble. It’s only returning the value of the first letter of the word. How can I make it iterate through the other letters and add them to the total? Here is my code:

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
  for l in word:
    l = l.lower()
    return score.get(l)
  total += score.get(l)
  return total

print scrabble_score("abc")

Thanks for your help!


#2

Hi @pagedw,

What is the purpose of this statement?

    return score.get(l)

#3

My thought was that it is needed to return the value of the letter?


#4

Yes, you do need to get the point value of the letter. However, when executed, a return statement immediately terminates execution of the function that contains it, and passes a value back to the statement that called the function. As you have it, this termination occurs during the first iteration of the for loop, and only the "a" is getting processed when you make this function call …

print scrabble_score("abc")

Within the function, this statement gets the value of the letter and adds it to total, however it is not indented sufficiently to make it part of the for loop …

  total += score.get(l)

Remove the return statement from the for loop since it terminates the function execution before it has completed its task, and because you already have a statement that would add each letter’s point value to total if you indent it correctly. You need two additional spaces of indentation there, so that its indentation matches that of this line …

    l = l.lower()

#5

Awesome! That makes sense and it works now. Thank you! As an (related) aside, when I indented the line total += score.get(l) simply by hitting ‘tab’, I got an error, but when I indented it by backspacing to the previous line and then hitting ‘enter/return’, the code works fine. Why is that?


#6

By default, Codecademy uses spaces for indentation. Mixing tabs and spaces for indentation doesn’t work well in Python, so use only spaces for indentation in Codecademy.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.