Why is this block of code now working? It’s only returning the value of the first letter, not adding all the letters scores together.

def scrabble_score(word):
  result = 0
  for x in word:
    for i in score:
      if x == i:
        result += score[i]
        return result


By default, a function returns none at the end of the function. If we want to return something else at the end of the function, we can use the return keyword. Thus, the function ends when a return keyword is reached

which means, in your scrabble_score function ends at the first iteration of the loop

but to get the correct scrabble score, the loop needs to make all its iterations (to add score of each letter successfully to result)

how do we go about fixing this with the inside i provided you?

answer partial copied from my earlier own answer:


I am totally tracking with you an appreciate your awesome community support!

So basically, the code is fine, but my function ends at the end of the first iteration.

So I need to figure out how to pull the return function out of the loop until all of the iterations are complete?


which is a bit too soon for the function to end, so the code is not entirely fine

yes :slight_smile: Given we need all the iterations of the loop to get to the correct result.



So by not indenting the return statement under the if statement, it will continue to run?

def scrabble_score(word):
  word = word.lower()
  total = 0
  for x in word:
    for i in score:
      if x == i:
        total = total + score[i]
  return total

9/15 scrabble_score

yep, given indent(ion) determine what is nested inside the for loop. The for loop will first execute everything within the for loop block before continuing with the code below the for loop block


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