![](/img/trans.png)
[英]How to write a python function to check if a user input for a password is not strong?
[英]Password check(strong or weak)
編寫確定密碼是否正確的函數。 我們將一個好的密碼定義為至少8個字符長,並且包含至少一個大寫字母,至少一個小寫字母和至少一個數字的密碼。
import string
num = [i for i in range(0,10)]
letdown = list(string.ascii_lowercase)
letup = list(string.ascii_uppercase)
def good_password(password):
l1=[]
l2=[]
l3=[]
for char in password:
if char in num:
l1.append(char)
elif char in letdown:
l2.append(char)
elif char in letup:
l3.append(char)
if len(l1)>=1 and len(l2) >=1 and len(l3) >=1 and len(password) >=8:
return True
else:
return False
這是我提出的代碼。 但是,它似乎不起作用,我無法說出原因。 誰能解釋我? 我仍然是編程的新手。
我想研究使用內置於.isdigit(), .isupper(), and .islower()
函數中的.isdigit(), .isupper(), and .islower()
這可以為您節省一些行來檢查那些條件的密碼。
另外,您還應將if
替換為elif
。 您的代碼現在是這樣,一旦滿足條件就不會檢查其余代碼。 因此,如果您希望滿足所有條件,則需要檢查每個條件是否正確。
編輯:正如弗雷德在下面指出的,第二部分在技術上不正確。 盡管有關if
vs. elif
的陳述是正確的,但出於Fred提到的原因,它不必在您的代碼中使用。
我相信使用“ any”方法會更好:
any(_.islower() for _ in passwrod) # checks that at least 1 character is in lowercase
any(_.isupper() for _ in passwrod) # checks that at least 1 character is in uppercase
any(_.isdigit() for _ in passwrod) # checks that at least 1 character is a number
您需要將int的' num '列表轉換為字符串列表。 因為您無法比較int和str
>>> '1' == 1
False
>>> '1' in [1,2]
False
更改
num = [i for i in range(0,10)]
至
num = map(str, [i for i in range(0,10)])
經過一些運行和測試之后,我得到了一個簡單的解決方案,正如其他用戶所說,str不等於數字,意味着0!=“ 0”,因此,您可以將第一個列表轉換為通過執行以下操作來包含數字的str:
num = [str(i) for i in range(0,10)]
現在您的列表是:
=> ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
最后,當您嘗試代碼時:
(我稍微改了個名字,以使自己動聽)
導入字符串num = [范圍(0,10)中i的str(i)] letdown = list(string.ascii_lowercase)letup = list(string.ascii_uppercase)
def good_password(password):
hasNum=False
hasUp=False
hasDown=False
for char in password:
if char in num:
hasNum = True
if char in letdown:
hasDown = True
if char in letup:
hasUp = True
return hasNum and hasDown and hasUp and (len(password) >= 8)
good_password("Hoooooola1")
=> True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.