2016-05-10 175 views
0

不,我不是在標題中詛咒。我需要創建一個密碼處理程序來檢查輸入是否符合某些條件,其中之一是它必須包含字符$ @!%& * _中的一個。 這是我目前有。

def pword(): 
    global password 
    global lower 
    global upper 
    global integer 

password = input("Please enter your password ") 
length = len(password) 
lower = sum([int(c.islower()) for c in password]) 
upper = sum([int(c.isupper()) for c in password]) 
integer = sum([int(c.isdigit()) for c in password]) 


def length(): 
    global password 
if len(password) < 8: 
    print("Your password is too short, please try again") 
elif len(password) > 24: 
    print("Your password is too long, please try again") 

def strength(): 
    global lower 
    global upper 
    global integer 
if (lower) < 2: 
    print("Please use a mixed case password with lower case letters") 
elif (upper) < 2: 
    print("Please use a mixed case password with UPPER case letters") 
elif (integer) < 2: 
    print("Please try adding numbers") 
else: 
    print("Strength Assessed - Your password is ok") 
+0

你可以用're.match(...)'標準庫的're'模塊中。請注意,您所匹配的某些符號在正則表達式的上下文中具有不同的含義,因此請務必將它們轉義 - 例如在匹配中使用''\ *''來查找文字'*'和''*''表示「0或更多次重複」。 https://docs.python.org/3.5/library/re.html#match-objects –

+0

順便說一下,除非你修改它們,否則你不需要爲函數內部的變量聲明'全局foo' - 它們[範圍分辨率規則]已經具有對全球的閱讀權限(http://stackoverflow.com/a/292502/149428)。你可以在'length()'和'strength()'中刪除所有的全局裝飾。 –

回答

0

這種事情會工作:

required='[email protected]!%&*_' 

def has_required(input): 
    for char in required: 
     if input.contains(char): 
      return True 
    return False 

has_required('Foo') 
0
must_have = '[email protected]!%&*_' 
if not any(c in must_have for c in password): 
    print("Please try adding %s." % must_have) 

any(c in must_have for c in password)將返回True如果password中的任何一個字符也是must_have,換句話說,它將返回True時,密碼是好的。因爲想要測試不好的密碼,我們在其前面放置了not以反轉測試。因此,print語句僅在此處針對錯誤密碼執行。

+1

謝謝,這工作 – vilty

0

您可以使用列表理解+內置的any()輕鬆實現此功能。

has_symbol = any([symbol in password for symbol in list('[email protected]!%&*_')]) 

或者多一點打散:

required_symbols = list('[email protected]!%&*_') 
has_symbol = any([symbol in password for symbol in required_symbols])