Python 从我的程序中获取我无法理解的错误
我正在为我的初级python类编写一个用于信用卡验证的程序,使用Luhn算法来输出用户输入的信用卡号码是否有效,并且我遇到了一些不知道如何修复的错误。任何比我聪明的人都能看出我的代码有什么问题吗。非常感谢大家Python 从我的程序中获取我无法理解的错误,python,Python,我正在为我的初级python类编写一个用于信用卡验证的程序,使用Luhn算法来输出用户输入的信用卡号码是否有效,并且我遇到了一些不知道如何修复的错误。任何比我聪明的人都能看出我的代码有什么问题吗。非常感谢大家 def main(): # user will input the credit card number as a string # call the function isValid() and print whether the credit card number i
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()
与此代码中的其他地方一样,您需要一个字符串:
str(number)[num]
而不是number[num]
我应该在哪里将number变量转换为str?将错误所指行中的number
替换为str(number)
(如我的回答中所述)。