Fall 2016 Credit Card Number Validation: The Luhn check or the Mod 10 check In 1
ID: 3782171 • Letter: F
Question
Fall 2016 Credit Card Number Validation: The Luhn check or the Mod 10 check In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine whether a card number is entered or scanned correctly. To ensure validity: Check to see that the number has 13-16 digits For certain companies, must start with a particular number: Going from RIGHT to LEFT, double every second digit. If doubling a digit results in a two-digit number, add up the two digits to get a single-digit number. Then ADD all of these single-digit numbers together rightarrow sumSecondDigits. Next, going from RIGHT to LEFT, add all digits in the ODD places rightarrow sumOddPlaces. Add the sumSecondDigits to the sumOddPlaces. If the result is divisible by 10, the card number is valid. Otherwise, it is invalid. Write a function called is ValidCreditCard that reads accepts a string and returns True if the string represents a valid credit card number and False if it is invalid. A function that accepts a string and returns the sum of the digits in the even places doubled A function that accepts a string and returns the sum of the digits in odd places A ¢ A function that accepts a string and returns the Prefix as a string (Visa, MC, Discover, AmEx). Others as you see fit Create a list of sample credit card numbers and call your function, printing the number and a message indicating if the number was valid or not. Here are some ideas about what to test: Too long Too short Valid 13-16 digit entry First character is a letter Beginning characters not valid (starts with letter, starts with # other than 4, 5, 6 or 37) Sum of sums not evenly divisible by 10 Valid Discover# 6312345678901 Valid Visa# 4388576018410707 Valid AmEx# Valid Mastercard #Explanation / Answer
def sumOfEven(cn):
s = 0
for i in range(1,len(cn),2):
dig = (int(cn[i]))*2
if (dig > 9):
dig = str(dig)
sdig = int(dig[0])+int(dig[1])
s += sdig
else:
s += dig
return s
def sumOfOdd(cn):
s = 0
for i in range(0,len(cn),2):
s += int(cn[i])
return s
cardNum = input("Enter the card number: ")
if(cardNum[0].isalpha()):
print("First character is a letter...")
else:
cn = int(cardNum)
if(12<len(cardNum)<17):
if(cardNum[0] == "4" or cardNum[0] == "5" or cardNum[0] == "6" or cardNum[:2] == "37" ):
se = sumOfEven(cardNum)
so = sumOfOdd(cardNum)
if((se+so)%10 == 0):
print("It is a valid card number.")
else:
print("Sum of sums is not evenly divisible by 10.")
print("It is not a valid card number.")
else:
print("Beginning digit of card number is not valid.")
else:
if(len(cardNum) < 6):
print("Too short...")
elif(len(cardNum) > 20):
print("Too long...")
else:
print("Card number length must be between 13 and 16.")
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.