信用卡检查练习python

iai*_*mcd 2 python python-3.x

对于免费的在线Python教程,我需要:

编写一个检查给定信用卡号是否有效的功能.该函数check(S)应该以字符串S作为输入.首先,如果字符串不遵循"#### #### #### ####"每个#都是数字的格式,那么它应该返回False.然后,如果数字的总和可以被10("校验和"方法)整除,那么程序应该返回True,否则它应该返回False.例如,如果S是字符串,"9384 3495 3297 0123"那么虽然格式正确,但数字总和是72你应该返回的False.

以下显示了我的想法.我认为我的逻辑是正确的,但不太明白为什么它给了我错误的价值.我的代码中是否存在结构问题,或者我使用的方法是否错误?

def check(S): 
    if len(S) != 19 and S[4] != '' and S[9] != '' and S[14] != '':
        return False                # checking if the format is correct

    S = S.replace(" ",'')         # Taking away spaces in the string
    if not S.isdigit():
        return False             # checking that the string has only numbers

    L = []            
    for i in S:
        i = int(i)                # Making a list out of the string and converting each character to an integer so that it the list can be summed 
        L.append(i)
    if sum(L)//10 != 0:        # checking to see if the sum of the list is divisible by 10
        return False
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

你没有测试空格,只测试字符串,当你在python字符串上使用直接索引时,你永远不会找到它.

此外,False如果这4个条件中的任何一个都是真的,你应该返回,而不是如果它们在同一时间都是真的:

if len(S) != 19 or S[4] != ' ' or S[9] != ' ' or S[14] != ' ':
    return False
Run Code Online (Sandbox Code Playgroud)

接下来,替换空格,但不要再次检查长度.如果我给你19个空格怎么办:

S = S.replace(" ", '')
if len(S) != 16 or not S.isdigit():
    return False
Run Code Online (Sandbox Code Playgroud)

最后,您要先收集所有数字,并检查是否有余数:

L = map(int, S)  # makes S into a sequence of integers in one step
if sum(L) % 10 != 0:  # % calculates the remainder, which should be 0
    return False
Run Code Online (Sandbox Code Playgroud)

如果所有这些测试都已通过,请不要忘记返回True:

return True
Run Code Online (Sandbox Code Playgroud)

在末尾.

把它们放在一起,你得到:

>>> def check(S):
...     if len(S) != 19 or S[4] != ' ' or S[9] != ' ' or S[14] != ' ':
...         return False
...     S = S.replace(" ", '')
...     if len(S) != 16 or not S.isdigit():
...         return False
...     L = map(int, S)  # makes S into a sequence of integers in one step
...     if sum(L) % 10 != 0:  # % calculates the remainder, which should be 0
...         return False
...     return True
... 
>>> check('9384 3495 3297 0123')
False
>>> check('9384 3495 3297 0121')
True
Run Code Online (Sandbox Code Playgroud)