Implement the Luhn Algorithm - Implement the Luhn Algorithm

Tell us what’s happening:

Technically my solution works, so there’s no issue I need help with. However, I figured I would ask if there is a better way to write this solution.

Your code so far

def verify_card_number(card_num):
    stripped_nums = card_num.replace(" ", "").replace("-", "")
    
    digits = [int(d) for d in stripped_nums]
    
    
    sum = 0
    even_digit = len(digits) % 2 == 0
    odd_digit = len(digits) % 2 != 0
    check_digit = len(digits) - 1
    i = len(digits) - 1
    doubled_index = i - 1
    while i >= 0:
        if even_digit:
            if i % 2 == 0:
                doubled_value = digits[i] * 2
                if doubled_value > 9:
                    doubled_value -= 9
                    sum += doubled_value
                else:
                    sum += doubled_value
            else:
                sum += digits[i]
        elif odd_digit:
            if i % 2 != 0:
                doubled_value = digits[i] * 2
                if doubled_value > 9:
                    doubled_value -= 9
                    sum += doubled_value
                else:
                    sum += doubled_value
            else:
                sum += digits[i]
        i -= 1
    
    if sum % 10 == 0:
        return 'VALID!'
    else:
        return 'INVALID!'

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36

Challenge Information:

Implement the Luhn Algorithm - Implement the Luhn Algorithm

That depends a bit what kind of better you’d like.

Currently the most sticking out are duplicated parts within the while loop, usually there’s some way to reduce duplication.

Second would be using while loop itself, when it’s not necessarily required. The for loop makes iteration more pleasant, without risking encountering one of the bugs that can sneak in, when manually handling incrementation with while loop.