根据给定标准验证信用卡号

时间:2019-04-07 03:10:49

标签: python

我已经学习Python一周了,这是我第一次进行一些编码。
正如标题所说,我遇到了这个问题。我为规则1和规则2编写的内容还可以,但是对于3和4则行不通。

给定的标准是:

  
      
  1. 如果第一个数字= 4,则通过或返回1(违反了第一条规则)
  2.   
  3. 如果进行第4次挖掘>第5次挖掘则通过或返回2(违反第二条规则)
  4.   
  5. 所有数字的总和必须被4整除或返回3
  6.   
  7. 如果您将前两位数字视为两位数字,并将第七位和第八位数字视为两位数字,则它们的总和必须为100或返回4
  8.   

像这样:

def verify(number) : # 
      x= int(number[0]+number[1]+number[2]+number[3])
      y= int(number[5]+number[6]+number[7]+number[8])
      z= int(number[11]+number[12]+number[13]+number[10])
      temp = int(x) + int(y) + int(z)
      temp2 = int(number[1]+number[0])
      temp3 = int(number[8]+number[7])
      sum1 = int(number[0])+int(number[1])+int(number[2])+int(number[3])+int(number[5])+int(number[6])+int(number[7])+int(number[8])+int(number[11])+int(number[10])+int(number[12])+int(number[13])

      sum2 = temp2 + temp3
      if int(number[0]) != 4:
          return 1
          #rule1
      elif int(number[3]) <= int(number[5]) and int(number[0]) == 4:
          return 2
          #rule2
      elif sum1 % 4 != 0 and number[3] > number[5] and number[0] == 4: 
          return 3
          #rule3
      elif sum1 % 4 == 0 and number[3] > number[5] and number[0] == 4 and sum2 != 100:
          return 4
          #rule4
      else:
          return True    

print("the entered credit number is","output")

input = "9000-0000-0000" #It can vary to test the code
output = verify(input)

对不起我的英语不好(我不是母语人士)

1 个答案:

答案 0 :(得分:1)

如何为所有数字的总和创建一个单独的函数,您对前两个要求非常正确:

def verify(number_str):
    # if 1st digit = 4 then passed or return 1 (violated 1st rule) 
    if int(number_str[0]) != 4:
        return 1
    # if 4th dig > 5th dig then passed or return 2 (violated 2nd rule)
    elif int(number_str[3]) <= int(number_str[5]):
        return 2
    # the sum of all digits must be evenly divisible by 4 or return 3  (violated 3rd rule)
    elif get_sum_of_digits(number_str) % 4 != 0:
        return 3
    # if you treat the first two digits as a two-digit number and the seventh
    # and eighth digits as a two-digit number, their sum must be 100 or return 4
    elif int(number_str[0:2]) + int(number_str[7:9]) != 100:
        return 4
    # the number is valid otherwise
    return True

def get_sum_of_digits(number_str):
    total = 0
    for char in number_str:
        if char.isdigit(): # to ignore the `-` characters
            total += int(char)
    return total

无效用法示例1:

input_number  = "9000-0000-0000"
output = verify(input_number)
if isinstance(output, bool):
    print("The entered credit number is valid.")
else:
    print(f"The entered credit number is not valid. Error code: {output}")

输出:

The entered credit number is not valid. Error code: 1

无效用法示例2:

input_number = "4007-6000-0000"

输出:

The entered credit number is not valid. Error code: 3

有效用法示例:

input_number = "4002-0060-0000"

输出:

The entered credit number is valid.