以下是密碼驗證過程的代碼,至少包含一個小寫字母,一個大寫字母和一個數字。如何在使用正則表達式時連接多個if語句?
import re
password=raw_input('Enter the Password')
x= (re.findall(r'[a-z]',password))
if len(x)==0:
print " at least one 'a-z' requirment not completed"
else:
#(what should i write here to connect this to the next step?)
y=(re.findall(r'[A-Z',password))
if len(y)==0:
print "at least one 'A-Z' requirement not completed"
else:
#(what should i write here?)
z=(re.findall(r'[0-9]',password))
if len(z)==0:
print "at least one '0-9' requirment not completed"
else:
print ' Good password!'
我的願望是讓Python的這樣一種方式,如果x
不爲0,然後繼續和驗證運行,如果y
等於0。如果不是,驗證z
不等於0。如果不,告訴用戶密碼是好的。
還有的這個更一般的重複,但在短期:包這一切的功能, 'len(x)= 0'部分的''return'函數早於該函數。那麼你不需要一個'else'子句,並且你只是遍歷每個'if語句'或者返回提前。 (你可以在最後返回'False'或者'True',然後你的函數就是'validate_password'。 – Evert
另一種方法是如果一個'if-elif-elif -...'鏈,並且移動'findall直接分配給該鏈:'elif len(re.findall(r'[A-Z',password))== 0:'等 – Evert
基本上,你的else子句應該是級聯的: – engineer14