pythonloops

Credit card validator program in python , loop


I’m working on a credit card validator program in Python using the Luhn’s Algorithm, but I’m stuck on the for loop part.

Here’s the full code I have so far:

# Credit card validator by Ahum Maitra

credit_card_number = input("Enter your credit card number : \n>")
sum_odd_digits = 0
sum_even_digits = 0
total = 0

# Replace any '-' or spaces with nothing
temp_credit_card_number = credit_card_number
temp_credit_card_number = temp_credit_card_number.replace("-", "")
temp_credit_card_number = temp_credit_card_number.replace(" ", "")
temp_credit_card_number = temp_credit_card_number[::-1]

# Convert each digit into an integer
temp_credit_card_number = [int(digit) for digit in temp_credit_card_number]

# Loop through each digit with its index
for index, digit in enumerate(temp_credit_card_number):
    if index % 2 == 0:
        sum_odd_digits += digit
    else:
        doubled = digit * 2
        if doubled > 9:
            doubled -= 9
        sum_even_digits += doubled

# Calculate the total
total = sum_even_digits + sum_odd_digits

# Check if valid
if total % 10 == 0:
    print("Valid")
else:
    print("Invalid")

The part I don’t understand is this section:

for index, digit in enumerate(temp_credit_card_number):
    if index % 2 == 0:
        sum_odd_digits += digit
    else:
        doubled = digit * 2
        if doubled > 9:
            doubled -= 9
        sum_even_digits += doubled

I get that it’s looping through the reversed credit card number, but I’m confused about:

Why check if index % 2 == 0?

How exactly is the else part (doubling, subtracting 9) working in the context of Luhn’s algorithm?

For reference, here’s the Luhn’s algorithm problem:

https://cs50.harvard.edu/x/psets/1/credit/

So, my question is , How digit and index variable works and how the for loop works and why we use index first then digit? It's supposed to work with digits like : digit % 2 == 0, why i % 2 == 0....and next step, why we use digits? How this function work?


Solution

  • Why check if index % 2 == 0?

    % is the modulus operator. It returns the remainder of index divided by 2. Checking for zero means it is even, else it is odd.

    How exactly is the else part (doubling, subtracting 9) working in the context of Luhn’s algorithm?

    When doubling a digit, if the result is a two-digit number, add those digits together. So if the digit is 6 and becomes 12, 1+2 = 3. Note that 12-9 is also 3. Checking that the number is greater than 9 and subtracting 9 is an algorithm for adding the digits together. Other examples: 5*2=10, 1+0=1, 10-9=1, 7*2=14, 1+4=5, 14-9=5...