Skip to content

Instantly share code, notes, and snippets.

@MohanSha
Created February 13, 2018 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohanSha/fada6f6c091cdf16859a733143205da3 to your computer and use it in GitHub Desktop.
Save MohanSha/fada6f6c091cdf16859a733143205da3 to your computer and use it in GitHub Desktop.
Takes in a credit card number from a common credit card vendor (Visa, MasterCard, American Express, Discoverer) and validates it to make sure that it is a valid number (look into how credit cards use a checksum).
def main():
credit_card_num = list(raw_input("Credit card #: "))
checksum_nums = [int(v) * 2 for i, v in enumerate(credit_card_num) if i % 2 == 0]
checksum = 0
for i, v in enumerate(credit_card_num):
checksum += (i % 2 != 0 and int(credit_card_num[i]) or 0)
for v in checksum_nums:
if v >= 10:
q, r = divmod(v, 10)
checksum += q + r
else:
checksum += v
if checksum % 10 == 0: print "The credit card number is valid."
else: print "The credit card number is not valid!"
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment