如何用Python编写程序验证卡片安全码?

3 投票
5 回答
1378 浏览
提问于 2025-04-18 03:38

我想写一个程序,用来验证信用卡上的安全码(CSC,通常是三位数字)。这个程序的功能很简单,就是检查输入的代码是否有效。有效的代码要求输入的三个字符都是0到9之间的数字。如果输入的安全码有效,程序会显示一条消息告诉你它是有效的;如果输入的代码不是三个数字,程序则会显示另一条消息告诉你它无效。

我写了以下代码,但我知道它有问题。我该怎么做才能让它正常工作,同时保持简单明了呢?

code = raw_input("Please enter CSC: ")

if code[0] in range [0,10] and code[1] in range [0,10] and code[2] in range [0,10]:
    print "Thank you. We will process your order!"
else:
    print "The verification code was not valid. Please check your credit card code again."

非常感谢你的帮助!

5 个回答

1

我决定这样做:

code = raw_input("Please enter CSC: ")

if len(code) == 3 and code[0] in map(str, range(0,10)) and code[1] in map(str, range(0,10)) and code[2] in map(str, range(0,10)):
    print "Thank you. We will process your order!"
else:
    print "The verification code was not valid. Please check your credit card code again."

这样是可以的,但这样做适用于所有情况吗?

非常感谢大家的回答!

1

你的代码差不多是对的,但还有更好的方法。把每个 range [0,10] 改成 map(str, range(0,10)),这样就能正常工作了。不过要注意,如果我输入 "123cucumbers",它会接受我的输入哦 :)

这可能是使用正则表达式的一个好机会,但老实说,我觉得用正则表达式有点过于复杂了。试试这个方法:

def validCSC(csc):
    if not len(csc) == 3:
        return False
    try:
        csc = int(csc) # turn it into a number
    except ValueError: # input isn't a number
        return False
    if 100 <= csc <= 999:
        return True
    else:
        return False
2

或者:

import re
if re.match("[0-9][0-9][0-9]", code) == None:
    print "Not valid"
else:
    Print "Valid"
2

使用一个正则表达式,来匹配 \d{3}

import re
m = re.match('\d{3}', code)
if m:
    print 'Yay!'
else:
    print 'Fail!'
2

你可以检查一下长度是否正确:

if len(code) == 3:

然后检查一下它是不是一个数字:

if code.isdigit():

补充:正确的语法:

if len(code) == 3 and code.isdigit():

撰写回答