Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 8 - More on Strings and Special Methods - Programming Exercises - Page 266: 8.14

Answer

code

Work Step by Step

# 8.14 (Financial: credit card number validation) Rewrite Exercise 6.29 using a string # input for a credit card number. def main(): number = input("Enter a credit card number as a string: ").strip() if isValid(number): print(number + " is valid") else: print(number + " is invalid") # Return true if the card number is valid def isValid(number): return (number.startswith("4") or number.startswith("5") or number.startswith("6") or number.startswith("37")) and \ (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0 # Get the result from Step 2 def sumOfDoubleEvenPlace(cardNumber): result = 0 for i in range(len(cardNumber) - 2, -1, - 2): result += getDigit(int(cardNumber[i]) * 2) return result # Return this number if it is a single digit, otherwise, return # the sum of the two digits def getDigit(number): return number % 10 + (number // 10 % 10) # Return sum of odd place digits in number def sumOfOddPlace(cardNumber): result = 0 for i in range(len(cardNumber) - 1, -1, -2): result += int(cardNumber[i]) return result main()
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.