Wrong return value


#1

Here is my code:

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

print scrabble_score("Pie")

And then the program gave me this error.

Your function fails on scrabble_score("pie").
It returns "3" when it should return "5".

How can I fix it?


How can I access a dictionary key value inside of a loop?
#2

please post your code with format so indent shows:

How do I format code in my posts?

and without all those underscores please, they are distracting.


#3

I managed to fix my format. Thanks for the information. I still have trouble using the backtick. Right now I can only use the 4 spaces method.


#5

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.

Given return is the last thing a function does, when a return keyword is reached, the function ends

so your function ends in the first iteration of your loop, is that desired if you want to get the total score?


#6

No. I want my function to loop over every

  char #Characters in the word 

in

  word 

while looping, I want my function to check how many points each character has and add it into

  total

and the points are written in

  score

#7

so how do you prevent return from ending the function in the first iteration of your loop? When should you return the score?


#8

I got it.

This quote makes me go back and read the article about the function of

return

Here is what I conclude.

  • It was not just putting the word “return” after the loop to end it.

  • According to my code

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

I returned only the value of the first time that the loop goes through the first character in the given word. And it stored inside the variable total which means

  1. The loop hit the first character of the word “Pie” which is “P”.
  2. The loop find the value of “P” in the dictionary score which is 3.
  3. The loop add 3 to total >>>> total = 0 + 3 = 3
  4. Because I told the loop to return the value of total inside the loop so after it calculated total = 3, it stored that value in total and returned that value to me.

Here is how I fix it.

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

print scrabble_score("Pie")

This way, I can make sure that the final value of total is the sum of all the letters in the given word. And make sure that I didn’t just put return inside the loop just to end it, but rather use it to store whatever the result of total is after it has gone through loop.


#9

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