2016-03-08 100 views
-1
def validate(s): 
    global Cap, Low, Num, Spec 
    ''' Checks whether the string s fits the 
     criteria for a valid password. 
    ''' 
    capital =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] 
    lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] 
    number = ['0','1','2','3','4','5','6','7','8','9'] 
    special =['@','$','#'] 

    for i in s: 
     if i in capital: 
      Cap = True 
     else: 
      Cap = False 
     if s in lowercase: 
      Low = True 
     else: 
      Low = False 
     if s in number: 
      Num = True 
     else: 
      Num = False 
     if s in special: 
      Spec = True 
     else: 
      Spec = False 

    if Cap and Low and Num and Spec is True: 
     return ('valid') 
    else: 
     return ('not valid') 



def main(): 
    ''' The program driver. ''' 

    # set cmd to anything except quit() 
    cmd = '' 

    # process the user commands 
    while cmd != 'quit': 
     cmd = input('> ') 
     password = cmd 
     validate(password) 


main() 

有人可以向我解釋爲什麼我的程序沒有返回「無效」或有效嗎?這個程序應該根據大寫,小寫,數字和特殊的要求來查看輸入是否是有效或無效的密碼。謝謝您的幫助。Python密碼要求計劃

+0

你在哪裏調用這個函數?另外,請按照書面說明修正縮進,「validate」是一個不起任何作用的函數,並且您從全局範圍返回,這似乎是錯誤的。 – ShadowRanger

+2

您不斷重新定義每封信的所有內容。只需在循環之前將每個變量定義爲「False」,並在循環中刪除所有「else」塊。另外,在'如果Cap和Low和Num ...'中,最後不需要'is True'。 – zondo

+1

此外,變量應該大概不是'全球性',除非一個單詞傳遞意味着所有後續單詞通過... – ShadowRanger

回答

1
  1. 請勿使用全局變量。將if ... else放置在該函數內。
  2. for循環之前將四個變量中的每一個初始化爲False。然後只有在條件滿足時纔將它們設置爲True。
  3. 您可以縮短字符列表。可以使用比較if 'A' <= i <= 'Z'或使用str.islower()str.isupper()str.isdigit()。對於特殊字符,您可以測試i是否在字符串中。
  4. 使用i(而不是s在測試中)
  5. 返回值不需要括在括號內。
  6. 您可以使用elif,因爲這四個類別是互斥的。

其中給出

def validate(s): 
    """ Checks whether the string s fits the 
    criteria for a valid password. Requires one of each 
    of the following: lowercase, uppercase, digit and special char 
    """ 
    special = '@$#' 

    Cap,Low,Num,Spec = False,False,False,False 
    for i in s: 
    if i.isupper(): 
     Cap = True 
    elif i.islower(): 
     Low = True 
    elif i.isdigit(): 
     Num = True 
    elif i in special: 
     Spec = True 

    if Cap and Low and Num and Spec: 
    return 'valid' 
    else: 
    return 'not valid' 

和驗證與(假設python3,使用raw_input爲python2)

p = input("Password?") 
print (validate(p)) 
-1

你的程序不會返回任何東西,因爲你沒有打印任何東西。除非你輸入quit,否則你的時間永遠循環。

def main(): 
    cmd = '' 
    while cmd != 'quit': 
     cmd = raw_input('> ') 
     isValid = validate(cmd) 
     print isValid 
     if isValid == 'valid': 
      return 

如果您正在使用python < 3.X使用raw_input。如果$ python script.py不起作用,請嘗試$ python -i script.py

希望這會有所幫助。

+0

這不會執行驗證檢查我猜他們正在做(要求密碼至少包含四個類中的每一個的一個字符)。 – ShadowRanger

+0

啊,我很抱歉錯過了那個,不適當的更新。 :) 感謝您指出了這一點。 – rrw