我正在使用Luhn算法为我的初学者python类编写程序,用于使用信用卡验证的信用卡验证,以输出用户输入的信用卡号是否有效,并且出现错误,我不知道如何解决。任何比我聪明的人都能看到我的代码有什么问题。非常感谢。
def main():
# user will input the credit card number as a string
# call the function isValid() and print whether the credit card number is valid or not valid
number = int(input("Enter a Credit Card Number as a Long Integer: "))
if isValid(number):
print(number, "is Valid.")
else:
print(number, "is Not Valid.")
def isValid(number):
# Return true if the card number is valid
# You will have to call function sumOfDoubleEvenPlace() and sumOfOddPlace()
return (str(number).startswith("4") or str(number).startswith("5") or str(number).startswith("37")) and \
(sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0
def sumOfDoubleEvenPlace(number):
# Sum of all single-digit numbers from step one
total = 0
for num in range(len(str(number)) -2, -1, -2):
total += getDigit(int(number[num]) * 2)
return total
def getDigit(number):
# Return the number if it is a single digit, otherwise return
# the sum of the two digits
return number % 10 + (number // 10 % 10)
def sumOfOddPlace(number):
total = 0
for num in range(len(number) -1, -1, -2):
total += int(number[num])
return total
main()
固定代码:
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()
答案 0 :(得分:0)
就像在此代码中的其他地方一样,您需要一个字符串:str(number)[num]
而不是number[num]
。