Trying to build a program in Python that sums the letters of a word based on the value of a letter


My project is looking at totaling the value of a word entered by a user based on assigned values for each letter. I’m struggling with getting the code to loop through each letter of the word and also sum the value for each letter. I’m still fairly new to Python so I’m unsure how much of it is correct or makes logical sense. Below is my code:

word = input("Enter a word:")
for j in range(len(word)):
    for i in range(len(letter_values)):
        if letter_values[i][0] in(word):
            word_value = letter_values[i][1]
    word_total = sum(word_value)

Any suggestions would be greatly appreciated!

Asked By: Garrett Kochner



You can use the python dictionaries, for example some like:

values = {"a": 1, "b":2, "c": 3, "d": 4}

You can access to the value of the letter ‘a’ using the key ‘a’:


An example:

values = {"a" : 1, "b" : 2, "c" : 3}
word = str(input("Enter a word:"))
total = 0
for letter in word:
    total += values[letter]

Your code is almost good. Your outer loop goes letter by letter in the word using j as an index. But j is never used in the inner loop. word_total should be outside the for loop. To fix, your code should look like.

for letter in word: # go letter by letter
    for inner_list in letter_values: 
        # brute force check for against every entry in letter_values
        if letter == inner_list[0]  # compare to letter
            word_value = inner_list[1]
word_total = sum(word_value)

I really like @BryanMontoyaOsorio’s solution with dictionaries. It’s elegant, easy to understand, and only a few lines of code.

The rest of this answer is a wonky way to generate a dictionary automatically. First Python has a built-in constant ascii_lowercase that contains all of the lowercase letters in the string module.

import string


And the random module can provide us with a list of values using the sample() method:

import random
value_list = random.sample(range(-26,26+1), 26)

[-15, -26, 20, 9, -9, -23, -7, 1, -25, 18, 13, 0, 2, 15, -14, -20, 12, -2, -17, 21, -16, -6, 8, 14, -5, -13]

So to generate a dictionary:

import string
import random

valdict = {} # create empty dictionary
value_list = random.sample(range(-26,26+1), 26)
for i, letter in enumerate(string.ascii_lowercase):
     valdict[letter] = value_list[i]


{'a': 4, 'b': -17, 'c': 11, 'd': -11, 'e': 10, 'f': 1, 'g': -18, 'h': -4, 'i': -13, 'j': 9, 'k': -20, 'l': 25, 'm': 17, 'n': 14, 'o': -2, 'p': -1, 'q': 6, 'r': -5, 's': -21, 't': -26, 'u': -19, 'v': 24, 'w': -12, 'x': -25, 'y': -14, 'z': 20}
Answered By: bfris
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.