2017-05-17 88 views
-1

我正在嘗試創建一個密碼重置程序,其中包括計算所述密碼中有多少個小寫字母和大寫字母。如果密碼少於8個字母或不包含大寫或小寫,它拒絕了密碼,但該程序崩潰時,有數字,因爲它無法計算有多少數字有:如何統計變量中的數字

import time 
print("Please create a new password") 
password = input() 
print("Re-enter your password") 
password2 = input() 
if password != password2: 
    print("Your Passwords Do Not Match") 
    time.sleep(2) 
    print("Please create a new password") 
    password = input() 
    print("Re-enter your password") 
    password2 = input() 
valid = 0 
lower = 0 
upper = 0 


for c in password: 
    if c.islower(): 
     lower += 1 
    elif c.isupper(): 
     upper += 1 
    else: 
     pass 

char_count = upper + lower 
if char_count >= 8: 
    valid += 1 
    if lower >= 1: 
     valid += 1 
    else: 
     print("Your Password Has No Lowercase Letters") 
    if upper >= 1: 
     valid += 1 
    else: 
     print("Your Password Has No Uppercase Letters") 


else: 
    print("Your Password Doesn't Have 8 Characters") 

if valid == 3: 
    print("Your Password Is Valid. Welcome") 
else: 
    print("Your Password Is Invalid. Sorry") 
    time.sleep(2) 
    print("Please create a new password") 
    password = input() 
    print("Re-enter your password") 
    password2 = input() 

編輯:謝謝你你的幫助,但我的計劃有效!多謝你們!

回答

1

您可以通過加總1 S/0秒的名單得到的密碼全部數字的計數,1意思的文字是一個數字,否則0

>>> password= "134jhie92" 
>>> sum([1 if c.isdigit() else 0 for c in password]) 
5 

或:

>>> sum(map(str.isdigit, password)) 
5 

這也可以與其它參數來實現:

lower = sum(map(str.islower, password)) 
upper = sum(map(str.isupper, password)) 
nums = sum(map(str.isdigit, password)) 

雖然這會更有意義,以延長您if陳述(由panatale1的建議):

lower = 0 
upper = 0 
nums = 0 

for c in password: 
    if c.islower(): 
     lower += 1 
    elif c.isupper(): 
     upper += 1 
    elif c.isdigit(): 
     nums += 1 
0

創建一個名爲num變量和更改for循環:

for c in password: 
    if c.isdigit(): 
     num += 1 
    elif c.islower(): 
     lower += 1 
    elif c.isupper(): 
     upper += 1 
    else: 
     pass 
相關問題