{"id":97,"date":"2022-05-02T22:12:25","date_gmt":"2022-05-02T22:12:25","guid":{"rendered":"https:\/\/codecrypt76.com\/?p=97"},"modified":"2022-11-25T16:52:02","modified_gmt":"2022-11-25T16:52:02","slug":"luhn-algorithm","status":"publish","type":"post","link":"https:\/\/codecrypt76.com\/index.php\/2022\/05\/02\/luhn-algorithm\/","title":{"rendered":"Credit Card Number Validator using Luhn Algorithm"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" width=\"1000\" height=\"420\" src=\"https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/creditcardValidator.webp\" alt=\"Credit Card Validator using Luhn Algorithm\" class=\"wp-image-99\" srcset=\"https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/creditcardValidator.webp 1000w, https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/creditcardValidator-300x126.webp 300w, https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/creditcardValidator-768x323.webp 768w\" sizes=\"(max-width: 1000px) 100vw, 1000px\" \/><figcaption>Credit Card Number Validator using Python and Luhn Algorithm<\/figcaption><\/figure>\n\n\n\n<h2>Using Python and Luhn Algorithm<\/h2>\n\n\n\n<p>The purpose of this article is to explain how to write a simple credit card validator using Python and the&nbsp;<em>Luhn algorithm<\/em>. Before we get into the code, lets discuss some background information about the Algorithm.<\/p>\n\n\n\n<h2 class=\"has-text-align-left\">About Luhn Algorithm<\/h2>\n\n\n\n<div class=\"wp-block-columns are-vertically-aligned-top\">\n<div class=\"wp-block-column is-vertically-aligned-top\" style=\"flex-basis:33.33%\">\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" src=\"https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/luhn.png\" alt=\"Hans Peter Luhn\" class=\"wp-image-100\" width=\"226\" height=\"290\" srcset=\"https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/luhn.png 253w, https:\/\/codecrypt76.com\/wp-content\/uploads\/2022\/04\/luhn-234x300.png 234w\" sizes=\"(max-width: 226px) 100vw, 226px\" \/><figcaption>Hans Peter Luhn<br>(July 1, 1896 \u2013 August 19, 1964)<\/figcaption><\/figure><\/div>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-vertically-aligned-top\" style=\"flex-basis:66.66%\">\n<p>In 1954, German computer scientist<a href=\"https:\/\/en.wikipedia.org\/wiki\/Hans_Peter_Luhn\" data-type=\"URL\" data-id=\"https:\/\/en.wikipedia.org\/wiki\/Hans_Peter_Luhn\" target=\"_blank\" rel=\"noreferrer noopener\"> Hans Peter Luhn<\/a> (seen on the left), developed the Luhn algorithm. Luhn was a researcher in the field of computer science and Library &amp; Information Science for IBM. Th algorithm also known as the \u201c<em>modulus 10 algorithm<\/em>,\u201d is a check sum formula used to validate a variety of identification numbers including credit card numbers.Most credit cards, and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers. It is not intended to be a cryptographically secure hash function; instead, it was created to detect accidental errors rather than defend against malicious attacks.<\/p>\n<\/div>\n<\/div>\n\n\n\n<h2>How the Algorithm Works<\/h2>\n\n\n\n<ol><li>The Luhn algorithm starts from the last digit which is called the&nbsp;<em>check digit<\/em>. Then moving from left to right (<em>immediately left<\/em>&nbsp;of the check digit), double the value of every digit at even indices.<\/li><li>If the result of this doubling operation is greater than 9 (e.g.,&nbsp;<em>6 \u00d7 2 = 12<\/em>), then subtract 9 from the result (e.g.,&nbsp;<em>12: 12 \u2212 9 = 3<\/em>) or, equivalently, add the digits of the result (e.g.,&nbsp;<em>12: 1 + 2 =3<\/em>).<\/li><li>Now sum all the digits (including the check digit).<\/li><li>If the total is divisible by 10 then the number is valid; otherwise, it is not valid.<\/li><\/ol>\n\n\n\n<h2><a href=\"https:\/\/dev.to\/seraph776\/credit-card-validator-using-python-4m6e-temp-slug-8628203?preview=248b6c88c3f8d689875d3dcab4a4ad365feb66f76e77c775ff8645a2febf81b91b72a46ef647a60b4b324a49df73fdfb631f76db382dcb08955ba551#implementing-luhns-algorithm-using-python\"><\/a>Implementing Luhn Algorithm using Python<\/h2>\n\n\n\n<p>The solution below will take a string argument called \u2018<em>credit_number<\/em>\u2018 which represent the credit card number that will be verified. The pseudo-code below will help explain the steps taken for each line of code.<\/p>\n\n\n\n<h2><a href=\"https:\/\/dev.to\/seraph776\/credit-card-validator-using-python-4m6e-temp-slug-8628203?preview=248b6c88c3f8d689875d3dcab4a4ad365feb66f76e77c775ff8645a2febf81b91b72a46ef647a60b4b324a49df73fdfb631f76db382dcb08955ba551#pseudocode\"><\/a>Pseudo-code<\/h2>\n\n\n\n<ol><li>Change string to list datatype<\/li><li>Remove last digit (<em>check digit<\/em>)<\/li><li>Reverse remaining digits<\/li><li>Double digits at even indices<\/li><li>Subtract 9 if over 9<\/li><li>Add the check digit back to the list<\/li><li>Sum all digits<\/li><li>If the sum is divisible by 10 then it is valid; otherwise, Invalid<\/li><\/ol>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-file=\"validate_credit_card.py\" data-lang=\"Python\"><code>def validate_credit_card(card_number: str) -&gt; bool:\n    &quot;&quot;&quot;This function validates a credit card number.&quot;&quot;&quot;\n    # 1. Change datatype to list[int]\n    card_number = [int(num) for num in card_number]\n\n    # 2. Remove the last digit:\n    checkDigit = card_number.pop(-1)\n\n    # 3. Reverse the remaining digits:\n    card_number.reverse()\n\n    # 4. Double digits at even indices\n    card_number = [num * 2 if idx % 2 == 0\n                   else num for idx, num in enumerate(card_number)]\n\n    # 5. Subtract 9 at even indices if digit is over 9\n    # (or you can add the digits)\n    card_number = [num - 9 if idx % 2 == 0 and num &gt;= 9\n                   else num for idx, num in enumerate(card_number)]\n\n    # 6. Add the checkDigit back to the list:\n    card_number.append(checkDigit)\n\n    # 7. Sum all digits:\n    checkSum = sum(card_number)\n\n    # 8. If checkSum is divisible by 10, it is valid.\n    return checkSum % 10 == 0\n\n\nif __name__ == &#39;__main__&#39;:\n    # American Express\n    print(validate_credit_card(&#39;378282246310005&#39;))  # True\n    print(validate_credit_card(&#39;371449635398431&#39;))  # True\n    # American Express Corporate\n    print(validate_credit_card(&#39;378734493671000&#39;))  # True\n    # Australian BankCard\n    print(validate_credit_card(&#39;5610591081018250&#39;))  # True\n    # Diners Club\n    print(validate_credit_card(&#39;30569309025904&#39;))  # True\n    print(validate_credit_card(&#39;38520000023237&#39;))  # True\n    # Discover\n    print(validate_credit_card(&#39;6011111111111117&#39;))  # True\n    print(validate_credit_card(&#39;6011000990139424&#39;))  # True\n    # MasterCard\n    print(validate_credit_card(&#39;5555555555554444&#39;))  # True\n    print(validate_credit_card(&#39;5105105105105100&#39;))  # True\n    # Visa\n    print(validate_credit_card(&#39;4111111111111111&#39;))  # True\n    print(validate_credit_card(&#39;4012888888881881&#39;))  # True\n\n    # Invalid Credit Card Number\n    print(validate_credit_card(&#39;7762888103111881&#39;))  # False\n    print(validate_credit_card(&#39;37612555227841800&#39;))  # False\n<\/code><\/pre><\/div>\n\n\n\n<p>This Code available at&nbsp;<a href=\"https:\/\/github.com\/seraph776\/credit_card_validator\">GitHub<\/a>. This is one solution on how to implement a simple credit card validator using Python. You can check the validity of the number using with this&nbsp;<a href=\"https:\/\/www.freeformatter.com\/credit-card-number-generator-validator.html\">credit card validator<\/a>.<\/p>\n\n\n\n<h2>Conclusion<\/h2>\n\n\n\n<p>This article discussed how to utilize the&nbsp;<em>Luhn Algorithm<\/em>&nbsp;and Python to validate credit card numbers. Hopefully you have a better understanding on how the algorithm works, and can write your own credit card number validator using Python. If not, there are available Python libraries that can be downloaded which would make it easier to include Luhn-based identification number verification in software applications.<\/p>\n\n\n\n<ul><li><a href=\"https:\/\/pypi.org\/project\/luhn\/\">luhn<\/a><\/li><li><a href=\"https:\/\/pypi.org\/project\/fast-luhn\/\">fast-luhn<\/a><\/li><\/ul>\n\n\n\n<p>If you found this article helpful or have any questions, please leave a comment.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to validate a credit card number using Python and Luhn Algorithm.  <\/p>\n","protected":false},"author":1,"featured_media":99,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[13,4],"tags":[9,31,32,33,34,11],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/posts\/97"}],"collection":[{"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/comments?post=97"}],"version-history":[{"count":20,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/posts\/97\/revisions"}],"predecessor-version":[{"id":134,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/posts\/97\/revisions\/134"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/media\/99"}],"wp:attachment":[{"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/media?parent=97"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/categories?post=97"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codecrypt76.com\/index.php\/wp-json\/wp\/v2\/tags?post=97"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}