简体   繁体   中英

how can I modify list item value using for loop in Python?

I'm trying to implement the Luhn algorithm in a program and I'm trying to modify list items if they are larger than 9. I will attach the code I'm trying to write. variable iin is defined outside of function.

def luhn_checker():
    account_number = random.randint(100000000, 999999999)
    check_sum = random.randint(0, 9)
    numbers = []
    card_number = f'{iin}{account_number}'

    for i in card_number:
        numbers.append(int(i))
        print(numbers)

    numbers[0] = numbers[0] * 2
    numbers[2] = numbers[2] * 2
    numbers[4] = numbers[4] * 2
    numbers[6] = numbers[6] * 2
    numbers[8] = numbers[8] * 2
    numbers[10] = numbers[10] * 2
    numbers[12] = numbers[12] * 2
    numbers[14] = numbers[14] * 2
    print(numbers)
    for i in numbers:
        if i > 9:
            numbers[i] = numbers[i] - 9

There is an error in your for-loop. It should be as follows:

for i, x in enumerate(numbers):
    numbers[i] = x - 9 if x > 9 else x

Thanks for the replies, ended up using a luhn library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM