#random password generator
import random
unified_code = "awertyuiosqpdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&*()_ "
passlength1=input("how long should your password be")
pass_length2=input("how long should your password be")
def generatrandompaassword():
length = random.randint(passlength1,pass_length2 )
password = ""
for index in range(length):
randomCharacter = random.choice(unified_code)
password = password randomCharacter
return password
passworder = generatrandompaassword()
print(passworder)
print("This is your new password")
由于某種原因,這不會讓我發布什么是評論
這是我幾天前開始使用 python 的代碼,所以我對它很陌生
拳頭我嘗試輸入一個變數,而不是詢問用戶輸入并將輸入插入程式并使用它來查找密碼應該多長的長度可以得到幫助嗎?
uj5u.com熱心網友回復:
代碼 - 您的代碼需要稍作改動
# random password generator
import random
unified_code = "awertyuiosqpdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&*()_ "
pass_length1 = int(input("What should be the min length your password be: "))
pass_length2 = int(input("What should be the max length your password be: "))
def generatrandompaassword():
length = random.randint(pass_length1, pass_length2 )
password = ""
for index in range(length):
randomCharacter = random.choice(unified_code)
password = password randomCharacter
return password
passworder = generatrandompaassword()
print(passworder)
print("This is your new password")
您從用戶那里收到的輸入是 type str,因此您需要將其轉換為int資料型別。
輸出
What should be the min length your password be: 5
What should be the max length your password be: 15
vyA7ROviA
This is your new password
建議:
- 堅持使用
_或camelCasing。pass_length1并且randomCharacter有兩種風格。 - 盡量讓你的函式名稱易于理解。使用
generate_random_password比generatrandompaassword - 給
=之前和之后一些空間。
閱讀一些有關 python PEP 標準的資訊,以使您的代碼更具可讀性。
uj5u.com熱心網友回復:
我重寫了你的代碼。您可以閱讀評論以了解發生了什么。本質上,我們有一個將在密碼中使用的字串列。然后我們詢問用戶密碼的長度,并將其轉換為數字。之后,我們遍歷長度并在密碼中添加一個隨機字符。
import random
characters = "awertyuiosqpdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&*()_ "
# Get the length of the password, and cast it to an integer so it can be used in the for loop ahead
length = int(input("how long should your password be? "))
def generatrandompaassword():
password = ""
# For every character in the password, get a random character and add that to the password
for i in range(length):
password = random.choice(characters)
return password
# Get the password
password = generatrandompaassword()
print("This is your new password: " password)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451549.html
上一篇:如何在函式內正確使用While?
