簡體   English   中英

使用 Python 的隨機密碼生成器

[英]Random Password Generator using Python

我正在創建一個隨機密碼生成器。 第一個我必須向用戶詢問密碼的長度,它必須至少有 8 位到最多 16 位。 我創建的一個是要求用戶輸入密碼本身,然后從那里檢查長度。 首先,我希望用戶輸入密碼的長度,例如:7 或 9 等。 如果用戶鍵入小於 8 且大於 16 的數字,則必須顯示“必須至少有 8 位到最多 16 位”。 請參考下面的代碼,如果不清楚,請參考這兩個圖像。 謝謝你。

輸入

import random
import string

print('hello, Welcome to Password generator!')

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

lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation

all = lower + upper + num + symbols

temp = random.sample(all,length)

password = "".join(temp)

print(password)

OUTPUT

hello, Welcome to Password generator!

Enter the length of password: 9
You password length is too short(must be more than 8 character)
1 is the length of your password

Enter the length of password: 9
You password length is too short(must be more than 8 character)
1 is the length of your password

input()的返回類型是str或 string。 當您檢查分配給length的返回值的長度時,它會計算字符串中的字符數,而不是檢查給定數字是大於還是小於另一個。 要解決此問題,請在length上調用 integer 構造函數int()或將其放在對input的調用周圍,以便在檢查之前將字符串轉換為數字類型。

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

此外,由於length現在是 integer,因此您無需調用len即可直接執行檢查。 例如

if length < 8:
    ...

你應該這樣寫:

lenght = int(input('insert lenght: '))

在 Python 中, int內置 function (也)用於將str轉換為 integer ( int ) 變量。

然后你必須這樣改變你的代碼:

print(lenght, "is the length of your password")

我會建議一些其他的改進。

all = lower + upper + num + symbols #Here you are overwriting the all built-in function

...或者...

while True: #Instead of "while not l"
    if (condition_that_will_end_the_loop):
        break

內置len function 返回一個int ,並以這種方式使用:

>>> len([1, 2, 3, 'hey'])
4
>>> len('string')
6

暫無
暫無

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

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