【问题标题】:Code python to check credit card and bank用python代码检查信用卡和银行
【发布时间】:2017-06-21 17:45:23
【问题描述】:

我正在编写一个小脚本来检查信用卡和银行有效性,但出于某种疯狂的原因,我收到了一个我不明白的错误。

#!/usr/bin/python
# -*- coding: utf-8 -*-
def digitSum(myString):

    length = len(myString)
    oddSum = 0
    evenSum = 0

    #base case
    if (length ==0):
        return 0

    #length > 0
    else:
        #if even
        if (length % 2 ==0):
            last = int(myString[-1])
            evenSum += last

            return evenSum + digitSum(myString[:-1])

        else:
            last = int(myString[-1])
            last = 2 * last
            part_sum = last // 10 + last % 10
            oddSum += part_sum

            return oddSum + digitSum(myString[:-1])


def luhns():
    myString = input("Entrez les 16 numéros de la Carte de Crédit ")

    total = digitSum(myString)
    if (total % 10 == 0):

        if total[:1] == "4":
            cardtype = "Visa"           
        if int(total[:2]) >= 51 and int(total[:2]) <= 55:
            cardtype = "Master Card"
        if total[:2] == "34" or total[:2] == "37":
            cardtype = "American Express"
        if total[:4] == "6011":
            cardtype = "Discover"
        if total[:2] == "36":
            cardtype = "DINERS"
        if int(total[:3]) >= 300 and int(total[:3]) <= 305:
            cardtype = "DINERS"

        return cardtype

        print ('Carte valide') + cardtype
    else:
        print ('Carte invalide')


def main():
    luhns()

#Python call to main()
main()

这是我得到的错误:

Entrez les 16 numéros de la Carte de Crédit 11111
Traceback (most recent call last):
  File "/Volumes/Python/LuhnsAlgorithm.py", line 61, in <module>
    main()
  File "/Volumes/Python/LuhnsAlgorithm.py", line 58, in main
    luhns()
  File "/Volumes/Python/LuhnsAlgorithm.py", line 34, in luhns
    total = digitSum(myString)
  File "/Volumes/Python/LuhnsAlgorithm.py", line 5, in digitSum
    length = len(myString)
TypeError: object of type 'int' has no len()
logout

【问题讨论】:

  • myString 是一个整数。
  • 不应该是raw_input吗?
  • 取决于您使用的是 Python 2 还是 Python 3,input 的行为有所不同。如果是整数,Python 2 input 将评估输入字符串并将其转换为整数。您必须使用 Python 2。如果您不想对其进行评估,则需要使用 raw_input。查看Differences between input and raw_input的答案
  • 当我输入11111 时,代码运行良好,输出为Carte invalide。如果您愿意,可以查看here

标签: python credit-card


【解决方案1】:

根据您使用的是 Python 2 还是 Python 3,input 的行为会有所不同。

Python 2 input 将评估输入字符串并将其转换为整数(如果它是整数)。

您可能正在使用 Python 2。

如果您不想对其进行评估,则需要使用 raw_input

查看Differences between input and raw_input的答案

【讨论】:

    【解决方案2】:

    首先,您的函数名称表明您尝试对数字求和。 然后你写 myString 作为参数,并试图找到那个字符串的长度。但是我认为您在调用并尝试查找该数字的长度时将 Numbers 传递给该函数,但实际上在 python 中您找不到数字的长度。

    所以你的错误在第 5 行。

    重新思考你的逻辑。

    【讨论】:

      猜你喜欢
      • 2015-11-06
      • 2012-09-27
      • 2014-10-16
      • 2022-10-04
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2022-08-15
      相关资源
      最近更新 更多