Scrabble_score help


#1

it's only showing score of first letter not the whole world ,plz help me get it ryt!

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def scrable_score(word):
l=word.lower()
for x in l:
total=0
total+=score[x]
return total
print scrable_score("sa")


#2

by placing total=0 inside the loop, total gets set back to zero each run/iteration of the loop, not retaining the value you add on the line below

Maybe a good idea to place total=0 outside the loop?


#3

hey! thanx it did work now!


#4

But do you also understand why it works?


#5

it would be great if you explain it to me, i have an idea about it but it's not crystal clear yet! and thanx for asking .


#6

look at this code, or rather run it:

x = [3,5,7]

for i in x:
   total = 0
   total += i
   print total

see how total gets re-assigned to zero each run/iteration of the loop? so in the first run of the loop i add 3 to total, then the next run of the loop total gets re-assigned to zero, and i add 5 to zero rather then adding 3 and 5 together which would result in a total

same happens with your code, because total gets set back to zero every time, it will never calculate the correct score for words longer then one letter, it the only gives the score of the last letter


#7

great ! thanx ,have a nyc day:slightly_smiling_face:


#8