checks validity of credit card in python (cs50 pset6) I'm new to using python and wanted to know how I could improve my program. I'm using the Luhn algorithm, the beginning numbers of the credit cards, and the number of digits in the credit card.
from cs50 import get_string
import re
import sys

number = get_string(&quot;NUMBER: &quot;)
check = []

if (len(number)) not in (13,15,16):
    print(&quot;INVALID&quot;)
    print(len(number))
    sys.exit(1)

for i in range(len(number)): # for the length of the string,
    if i%2 == (-2+len(number))%2: # if a counter is modulo 1
        digits = str(int(number[i])*2) #obtains the value of the multiplication
        for j in range(len(digits)):
            check.append(int(digits[j]))
    else:
        check.append(int(number[i]))

total = str(sum(check))


if re.search(&quot;0$&quot;, total):
    if re.search(&quot;^3(4|7)&quot;, number):
        print(&quot;AMEX&quot;)
    elif number[0] == str(4):
        print(&quot;VISA&quot;)
    elif re.search(&quot;^5(1|2|3|4|5)&quot;, number):
        print(&quot;MASTERCARD&quot;)
else:
    print(&quot;INVALID&quot;)
Your program would benefit from breaking up logic into functions. This also eliminates the global variables involved.
if i%2 == (-2+len(number))%2

This line is strange and not immediately obvious what it's doing. A reversed iteration would be easier to understand.
import re

def luhn_digit(digit,double):
    if double:
        doubled = digit*2
        return doubled-9 if doubled&gt;9 else doubled
    else:
        return digit

def is_valid_luhn(card):
    check_digit = int(card[-1])
    luhn_sum = sum([
        luhn_digit(int(digit),i%2==0)
        for i,digit in enumerate(reversed(card[:-1]))
    ])
    total = check_digit+luhn_sum
    return total%10==0

def is_valid_card(card):
    return (
        len(card) in (13,15,16) and
        is_valid_luhn(card)
    )

def get_card_type(card):
    if not is_valid_card(card):
        return &quot;INVALID&quot;
    if re.search(&quot;^3(4|7)&quot;, card):
        return &quot;AMEX&quot;
    if card[0] == str(4):
        return &quot;VISA&quot;
    if re.search(&quot;^5(1|2|3|4|5)&quot;, card):
        return &quot;MASTERCARD&quot;
    return &quot;INVALID&quot;

print(get_card_type(input(&quot;NUMBER: &quot;)))