Quotation over looping variable


Hello everyone. I'm having trouble with using a quoted index for looping.

I expected that score["i"] would access the value it corresponds to in the dictionary. The code only runs when "i" is without the quotation.

However, when I do print (score[i]) to test on an empty script (with the same dictionary), an error occurs, and I would have to do print(score["i"]) to access the value. Why is it different when I am looping?

I hope this makes sense.


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

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


Remove the quotation marks from the variable.

total += score[i]


Thanks mtf, I know that would fix it. But why exactly does it work without the quotation?

If do it the following 'long' way, with word = 'pie'

total = score[p] + score[i] + score[e],

an error would occur and not work without the quotations.


It works without quotes because i is a variable that contains one letter at a time.

This will work, but it is not dynamic. We want the function to work with any word.

total = score['p'] +  score['i'] +  score['e'],


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