Quotation over looping variable


#1



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.


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/3?curriculum_id=4f89dab3d788890003000096#


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


#2

Remove the quotation marks from the variable.

total += score[i]

#3

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.


#4

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'],

#5

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