Luhns Algorithm
<p>Hey I am doing Luhn's algorithm for an assignment for school.</p>

<p>A few outputs are coming out the correct way; however, some are not. </p>

<p><code>0004222222222222</code> is giving me a total of <code>44</code>, </p>

<p>and</p>

<p><code>0378282246310005</code> is giving me a total of <code>48</code>, </p>

<p>for a few examples.</p>

<p>I know my code isn't the cleanest as I am a novice but if anyone can identify where I'm getting my error I'd really appreciate</p>

<p>Here is my code: </p>

<pre><code>cardNumber = input( "What is your card number? ")
digit = len(cardNumber)
value = 0
total = 0
while ( len( cardNumber ) == 16 and digit &gt; 0):
    # HANDLE even digit positions
    if ( digit % 2 == 0 ):
        value = ( int( cardNumber[digit - 1]) * 2 )
        if( value &gt; 9 ):
            double = str( value )
            value = int( double[:1] ) + int( double[-1] )
            total = total + value
            value = 0
            digit = digit - 1
        else:
            total = total + value
            value = 0
            digit = digit - 1
    # HANDLE odd digit positions
    elif ( digit % 2 != 0):
        total = total + int( cardNumber[digit - 1] )
        digit = digit - 1
</code></pre>

<p>So your code is mostly correct, the only issue is that you haven't properly defined what should be considered an "odd" and an "even" number. As you read the number from the end, "odd and even" are also relative from the end, so  :</p>

<ul>
<li>odd numbers start from the <em>last one</em>, and then every other one </li>
<li>even numbers start from the <em>last but one</em>, and then every other one </li>
</ul>

<p>Example : 1234 is EOEO, 12345 is OEOEO (O means odd , E means even)</p>

<p>Here the fixed code (I only modified three lines, see comments):</p>

<pre><code>digit = len(cardNumber)
value = 0
total = 0
while  digit &gt; 0: # I removed the length condition
    # HANDLE even digit positions
    if ( (len(cardNumber)+1-digit) % 2 == 0 ): # &lt;- modification here
        value = ( int( cardNumber[digit - 1]) * 2 )
        if( value &gt; 9 ):
            double = str( value )
            value = int( double[:1] ) + int( double[-1] )
            total = total + value
            digit = digit - 1
        else:
            total = total + value
            digit = digit - 1

    # HANDLE odd digit positions
    elif ( (len(cardNumber)+1-digit) % 2 != 0): # &lt;- modification here
        value=int( cardNumber[digit - 1] )
        total = total + int( cardNumber[digit - 1] )
        digit = digit - 1

return total
</code></pre>

<p>Some tests :</p>

<pre><code>In : '0378282246310005' -&gt;  Out : 60
In : '00378282246310005' -&gt;  Out : 60
In : '0004222222222222' -&gt;  Out : 40
</code></pre>

python luhn