How to ensure repeated characters are accounted for in a for loop in python
<p>I'm working through the exercises in a textbook and I'm asked to create a numerology program that takes a name, assigns each letter a value based on ascending order in the alphabet and returns the sum of the letters. </p>

<p>The code I've written works fine for any name that doesn't repeat a letter. For example if the name is 'kayla', I know the if statement will stop at the first instance of 'a'. Is there a way within its current design to catch multiple letters or does it need to sort through the letters a different way?</p>

<pre><code>def main():

   alphabet = 'abcdefghijklmnopqrstuvwxyxz'
   user_name = raw_input('Please enter your name ')
   value = sum = 0

   for char in alphabet:
      value = value + 1
      if char in user_name:
          sum = sum + value

   print sum
</code></pre>

<p>The <code>in</code> function only verifies if an element is present in a list. You can resolve the problem in a lot of ways but I think a good approach to learn is to create a dictionary to store letter, value pairs and then iterate over the name characters to sum the values:</p>

<pre><code>def main():
   alphabet = 'abcdefghijklmnopqrstuvwxyxz'
   values, val = {}, 1
   for char in alphabet:
       values[char] = val
       val += 1
   print values
   user_name = raw_input('Please enter your name ')
   value = sum = 0

   for char in user_name.lower():
       sum += values[char]

   print sum

if __name__ == '__main__':
    main()
</code></pre>

<p>Another form is using index string function to get the value of the position of the letter in the string.
Here is the example code:</p>

<pre><code>def main():
    alphabet = 'abcdefghijklmnopqrstuvwxyxz'
    user_name = raw_input('Please enter your name ')
    sum = 0

    for char in user_name.lower():
        sum += alphabet.index(char) + 1
    print sum

if __name__ == '__main__':
    main()
</code></pre>

python for-loop