[Python] Credit card validator program in python , loop

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    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/

    Could someone please explain this loop in a beginner-friendly way?

    Continue reading...

Compartilhe esta Página