如何验证以 2 个数字开头的用户输入?

How do i validate user input that starts with 2 numbers?

我已尝试验证我的家庭作业的一些输入。 要求:

我已经尝试 len(number) 从用户输入中查找位数。但是,我不断收到错误 "invalid syntax"

    number = int(input("Enter your credit card number :"))

    if len(number) = 16 and number.startswith(4):
        validity = "valid"
    if len(number) = 15 and number.startswith(34) and number.startswith(37):
        validity = "valid"
    else:
        validity = "invalid"

我似乎得不到我想要的正确结果。

程序应该这样 运行:

    Enter your credit card number : 432143214321432
    You have entered an invalid Amex card numbers
    Enter your credit card number : 3456345634563456
    You have entered an invalid Visa card numbers
    Enter your credit card number : 123
    You have entered an invalid credit card number
    Enter your credit card number : 4321432143214321
    You have a valid Visa card and the last 4 digit is 4321

在这种情况下,将其作为字符串然后将其转换为 int 更容易。另一个错误是“=”运算符,它是一个赋值运算符,如果你想比较你需要使用双等号“==”:

number =input("Enter your credit card number :")

if len(number) == 16 and number.startswith('4'): # this will get executed if the length equal 16 and the number starts with 4
    validity = "valid"
if len(number) == 15 and number.startswith('34') or number.startswith('37'):
    validity = "valid"
else:
    validity = "invalid"

This would be a simpler code for your problem. also '=' is an assignment operator and for comparisons use'==' always.

  number=input()

  if len(number)==15 and (number.startswith('34') or number.startswith('37')):
       print("Valid AMEX card")
  elif len(number)==16 and number.startswith('4'):
       print("valid Visa card")
  else:
       print("invalid card")
if len(number) = 16 and number.startswith(4):
  • len(number)。 Number 没有 len,所以要么在此处将 number 转换为字符串,要么一开始就不要将其转换为 int
  • number.startswith(4):。同样,整数没有 startswith() 方法
  • ==是比较运算符,不是=
    number = input("Enter your credit card number :")

    if len(number) == 16 and number.startswith('4'):
        validity = "valid"
    if len(number) == 15 and number.startswith('34') or number.startswith('37'):
        validity = "valid"
    else:
        validity = "invalid"

如果您需要整数形式的数字(信用卡号不太可能),请将其转换为 number = int(number)

我建议编写一个函数来使用逻辑流验证您的输入。该函数应避免使用 else 语句。如果您匹配正确的输入,函数应该 return。如果没有输入匹配 return "invalid"。这样您就不需要尝试验证所有不正确的输入。

在函数 match/validate 中使用正则表达式,这是一个很好的方法,因为您可以轻松快速地检查数字和字符串。

首先我们需要检查输入的是15位还是16位。我们有 2 个独立的分支匹配。在第一个中我们匹配 15 个数字,在第二个中我们匹配 16 个数字。

在15位分支中,需要检查输入是否以34或37开头和returnAMEX,或者无效的AMEX。 在16位分支中,需要检查输入是否以4和return VISA开头,或者无效的VISA。

语法 card_number[:2] 是在 python 中使用一段字符串,您可以阅读更多关于 python 将它串成 here.

很容易在 15 位和 16 位分支中输入和 else,但是我总是发现当检查明确时更容易阅读。

如果我们没有匹配到任何好的卡片格式,默认为return "invalid".

我建议您阅读并熟悉正则表达式,因为它非常强大,而且可以非常快。它还支持多种语言和操作系统。

https://docs.python.org/2/library/re.html

import re

def validate(card_number):
    # we convert the input to a string
    card_number = str(card_number)
    if re.match('^\d{15}$', card_number):
        if re.match('^(34|37)', card_number[:2]):
            # starts with 34 / 37 and has 15 digits: AMEX card
            return 'AMEX Card and end with %s' % card_number[-4:]
        if not re.match('34|37', card_number[:2]):
            # if card number with 15 digits but does not start with 34, 37, print: You have entered an invalid Amex card numbers
            return 'INVALID AMEX Card'
    if re.match('^\d{16}$', card_number):
        if re.match('^4', card_number[:1]):
            # starts with 4 and has 16 digits: VISA card
            return 'VISA Card and end with %s' % card_number[-4:]
        if not re.match('4', card_number[:1]):
            # if card number with 16 digits but does not start with 4, print: You have entered an invalid Visa card numbers
            return 'INVALID VISA Card'
    # Card numbers that are not 15 or 16 digits, print: You have entered an invalid credit card number
    return 'Invalid CC Number'

在这里我们可以看到验证函数在工作。

>>> validate('345634563456345')
'AMEX Card and end with 6345'
>>> validate(345634563456345)
'AMEX Card and end with 6345'
>>> validate('432143214321432')
'INVALID AMEX Card'
>>> validate('545634563456345')
'INVALID AMEX Card'
>>> validate('3456345634563456')
'INVALID VISA Card'
>>> validate('4321432143214320')
'VISA Card and end with 4320'
>>> validate('5556345634563456')
'INVALID VISA Card'
>>> validate('123')
'Invalid CC Number'
>>> validate('nothing')
'Invalid CC Number'
  • 使用==比较
  • 不要将 input 转换为 int
  • 我输入 tryexception 以确保用户只输入整数

所以,更新后的代码是:

number = input("Enter number your credit card number:\n")
def card(number):
    try:
        if len(number) == 16 and number.startswith('4'):
            print("Valid VISA")
        elif len(number) == 15 and number.startswith('34') or number.startswith('37'):
            print("Valid Amex")
        else:
            print("Invalid")
    except ValueError:
        print("Enter only numbers")
card(number)