Your function fails on scrabble_score("DuNe")


#1

Hi....Below is my code:

It outputs the correct value but it always throw the error saying:
Enter a word with no spaces: Hi
5
Oops, try again. Your function fails on scrabble_score("DuNe"). It returns "2" when it should return "5"

Later I added the line to make the string lower case inside the function scrabble_score and it doesn't throw the error now...

Why did it throw the error when "string = string.lower()" added outside the function and it did not when added "word = word.lower()" inside the function?
Please someone help here....


9. scrabble_score
#2

The cause of the error is that the SCT is using direct inputs, not raw_input() to test the code. It's input goes to the word variable directly. That's why we much change the case inside the function.

Consider also, that once the case is changed to lower, it matches the keys in the score list. As a result, we do not need a nested for..in statement. assign the value at that key. To be sure this will not accept errant inputs, we can add a conditional to the opening line:

def scrabble_score(word):
    if word.isalpha() and len(word) > 0:
        word = word.lower()
        total = 0
        for char in word:
            total += score[char]
        return total
    else:
        return "Input Error!"

This is only an illustration. You are free to take from it whatever you can use.


#3

@mtf

I think you mixed up your programming languages, shouldn't it be and not &&?


#4

A refactored solution from the above (not meant as lesson code, only example)...

def word_score(w):
    return sum([score[c] for c in w.lower()]) if w.isalpha() and len(w) > 0 else "Input Error!"

print(word_score("x-ray"))     # Input Error!
print(word_score("XRAY"))      # 14

Should we be in a situation of absolutely trusting the inputs (perhaps they are validated before calling the function) we can shorten the code considerably:

def word_score(w):
    return sum([score[c] for c in w.lower()])