簡體   English   中英

帶字數限制的隨機密碼生成器

[英]Random password generator with words limit

我正在創建一個隨機密碼生成器。 我想創建一個輸入字段,其中密碼的長度只能是最小 8 和最大 16。如果用戶輸入的長度不是允許的長度,它會一直要求用戶輸入正確的密碼長度。 我使用 'return' 所以它返回到length = int(input('\nEnter the length of password: ')) ,但它在這里不起作用。 我可以就如何做到這一點獲得建議嗎?

#input the length of password
#must be minimun 8 to maximun 16

length = int(input('\nEnter the length of password: '))

#if use enter less than 8 or more than 16 

if length < 8 :
        print('You password length is too short(must be more than 8 character)')
        return;
elif length > 16:
        print('You password length is too long(must be less than 17 character)')
        return;
else:
        print('You password length looks good') 
    

改用內置的len函數並使用 while 循環:

#input the length of password
#must be minimun 8 to maximun 16

#if use enter less than 8 or more than 16
l = False
while not l:
    length = input('\nEnter the length of password: ')
    if len(length) < 8 :
        print('You password length is too short(must be more than 8 character)')
        print(len(length), "is the length of your password")
    elif len(length) > 16:
            print('You password length is too long(must be less than 17 character)')
            print(len(length), "is the length of your password")
    else:
            print('You password length looks good')
            break
        

輸出:

Enter the length of password: thisismorethan16characters
You password length is too long(must be less than 17 character)
26 is the length of your password

Enter the length of password: thisisgood
You password length looks good
>>> 

此外,刪除int()以便我們可以允許用戶輸入字符串,並且通常在函數中使用return 也沒有使用; 在蟒蛇。

代碼將一直運行,直到您提供正確的密碼

代碼將一直運行,直到您輸入正確的密碼。 我聲明了一個設置為 false 的變量 correct_pass。 當用戶輸入正確的密碼時,while 循環中的條件 correct_pass == False 當用戶輸入正確的密碼時,correct_pass 的值更改為 True,因此它退出循環,在其他情況下,它的值保持不變

correct_pass=False

while(correct_pass==False):
      length = input('\nEnter the length of password: ')
if len(length) < 8 :
    print('You password length is too short(must be more than 8 character)')
    correct_pass=False
elif len(length) < 8:
    print('You password length is too long(must be less than 17 character)')
    correct_pass=False
else:
    print('You password length looks good')
    correct_pass=True

您的代碼基本上使用整數值而不是用戶輸入的長度或整數數。

假設我輸入 9 作為輸入。

然后,您正在使用 If-elif-else 塊。

如果長度(當前用戶輸入為 9)<8,則打印“您的密碼長度太短”。 在我們的例子中,長度等於 9,也小於 17。所以我們滿足條件。

但是如果我們輸入例如 0, 2222。這顯然比您的代碼要求的值大得多。 我希望我把你的錯誤說清楚了。 現在,解決方法是:查看此評論

mn= input("請選擇密碼") pi= len(mn)

if pi>16 or pi<8: print("對不起!您的密碼長度必須在 8 到 16 個字符之間!")

否則:打印(“歡迎!”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM