Validate Credit Card Number Using Luhn Algorithm Python
<p>I am trying to implement Luhn algorithm in Python. Here is my code</p>

<pre><code>def validate(n):
    if len(str(n)) &gt; 16:
        return False
    else:
        if len(str(n)) % 2 == 0:
            for i in str(n[0::2]):
                digit = int(str(n[i])) * 2
                while digit &gt; 9:
                    digit = sum(map(int, str(digit)))
            dig_sum = sum(map(int, str(n)))
            return True if dig_sum % 10 == 0 else False
        elif len(str(n)) % 2 != 0:
            for i in str(n[1::2]):
                digit = int(str(n[i])) * 2
                while digit &gt; 9:
                    digit = sum(map(int, str(digit)))
            dig_sum = sum(map(int, str(n)))
            return True if dig_sum % 10 == 0 else False
</code></pre>

<p>I keep getting the error</p>

<pre><code>TypeError: 'int' object has no attribute '__getitem__
</code></pre>

<p>It is hard to tell without the complete error message, but it is likely because you confused in some places where you put the indexing and where you put the string conversion, for example: <code>for i in str(**n[1::2]**)</code> and <code>digit = int(str(**n[i]**)) * 2</code></p>

<p>A good way to handle it is to just create a temporary variable <code>n_str = str(n)</code>, and use it instead of str(n) over and over again.</p>

python algorithm