Validating Credit Card Numbers

  • + 0 comments

    Self-documenting code is ostensibly written using human-readable names, typically consisting of a phrase in a human language which reflects the symbol's meaning, such as article.

    import re
    
    def is_valid_credit_card(card_number: str) -> str:
        """Check if the card_number is valid or not,
        valid number has the following characteristics:
        It must start with a 4, 5 or 6.
        It must contain exactly 16 digits.
        It must only consist of digits (0-9).
        It may have digits in groups of 4, separated ONLY by one hyphen "-".
        It must NOT have 4 or more consecutive repeated digits.
        """
        pattern = re.compile(r'^(?!.*(\d)(-?\1){3})[456]\d{3}-?\d{4}-?\d{4}-?\d{4}$')
        if pattern.match(card_number):
            return "Valid"
        return "Invalid"
    
    number_of_cards = int(input())
    for _ in range(number_of_cards):
        card_to_check = input()
        print(is_valid_credit_card(card_to_check))