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>You almost got it right. Only that the last digit (or first from behind) should be considered as odd for your 16 digit card. So you should set:</p>

<pre><code>digit = len(cardNumber) - 1
</code></pre>

<p>And then your <em>while</em> condition should stop at <code>&gt;= 0</code> (zeroth item inclusive); note that the <code>len( cardNumber ) == 16</code> is redundant as the length of the card is constant:</p>

<pre><code>while digit &gt;= 0:
</code></pre>

<p>And finally your indexing of the creditcard number will no longer need a minus 1:</p>

<pre><code>value = int(cardNumber[digit]) * 2
...
...
total = total + int(cardNumber[digit])
</code></pre>

python luhn