Creating python scrabble function

Question:

I’m trying to create a scrabble function that takes a string of letters and returns the score based on the letters.
This is my code so far:

def scrabble_score(rack):
    count = 0
    for letter in rack:
        if letter == "EAIONRTLSU":
            count += 1
            return count
        elif letter == "DG":
            count += 2
            return count
        elif letter == "BCMP":
            count += 3
            return count        
        elif letter == "FHVWY":
            count += 4
            return count
        elif letter == "K":
            count += 5
            return count
        elif letter == "JX":
            count += 8
            return count
        else:
            letter == "QZ"
            count += 10
            return count

However when I tried to call the function

    scrabble_score("AABBWOL")

it returns 10 when it should return 14?

Asked By: J.Hansen

||

Answers:

The code has two issues:

  • The return statement should be called only one time, after the for iteration ends, so it can sum all the letter values
  • each if statement should check if the letter is in the string, not if it is equal to the list of letters with a specific value.

Then it would look like:

def scrabble_score(rack):
    count = 0
    for letter in rack:
        print letter
        if letter in "EAIONRTLSU":
            count += 1
        elif letter in "DG":
            count += 2
        elif letter in "BCMP":
            count += 3
        elif letter in "FHVWY":
            count += 4
        elif letter in "K":
            count += 5
        elif letter in "JX":
            count += 8
        else:
            count += 10
    return count

returning: 14

Answered By: marcanuy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.