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>Since you are working through a textbook, and I presume don't just want the answer, here is a hint.  You are iterating (looping) over the wrong thing.  You should be looping over <code>user_name</code>, not <code>alphabet</code>.</p>

<p><strong>Update</strong>.  If you want a nice "Pythonic" solution to your problem, this is one way:</p>

<pre><code>user_name = raw_input('Please enter your name ')
print sum(ord(letter.upper())-64 for letter in user_name)
</code></pre>

<p><strong>Explanation</strong>:</p>

<ol>
<li><code>ord</code> returns an ASCII code for a character, such as <code>65</code> for <code>'A'</code></li>
<li>ASCII codes for A-Z are 65 through 90, in just the right order</li>
<li>Subtracting 64 gives you <code>1</code> for <code>A</code>, <code>2</code> for <code>B</code>, and so on</li>
<li><code>sum</code> is a built-in function that does just what you would expect</li>
<li>the parameter to <code>sum</code> is an expression that evaluates to a sequence of numbers, one for each of the letters in <code>user_name</code></li>
</ol>

python for-loop