如何为密码或IC等第一个字符必须是特定字母和字符的东西添加验证



在读取csv文件之前,我想检查ic是否正确。以下是我迄今为止所做的:

nric = input("Enter your NRIC number: ")
def checklength(): #defining the checking of length of nric characters
return len(nric) == 9
def checkfirstcharac():
firstcharac = ["S", "T"]
return nric[0] == firstcharac
while not checklength() and checkfirstcharac():
print("Your nric input is not valid, please make the following corrections:")
if not checklength():
print("NRIC must be 9 characters long.")
if not checkfirstcharac():
print("NRIC must start with either an S or T.")
nric = input("Enter your NRIC number: ")

首先,如果你没有正确检查S t是否是第一个字母,你会检查第一个字母=列表["S","t"],而不是检查第一个字符是否在列表中,所以你会想要这个:

def checkfirstcharac():
firstcharac = ["S", "T"]
return nric[0] in firstcharac

你的while循环应该是这样的:

valid = False
while valid == False:
nric = input("Enter your NRIC number: ")
if not checklength() or not checkfirstcharac():
print("Your nric input is not valid, please make the following corrections:")
if not checklength():
print("NRIC must be 9 characters long.")
if not checkfirstcharac():
print("NRIC must start with either an S or T.")
else:
valid = True # this will break the loop

最新更新