簡體   English   中英

如何讓程序要求用戶輸入長度並使用輸入來生成密碼,只要用戶願意

[英]how to make the program ask the user for a input for length and use the input to make the password as long as the user would like

#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 編寫的代碼,所以我對它很陌生

首先,我嘗試放置一個變量,而不是要求用戶輸入並將輸入插入程序並使用它來查找密碼應該多長的長度可以獲得幫助嗎?

我重寫了你的代碼。 您可以閱讀評論以了解發生了什么。 本質上,我們有一個將在密碼中使用的字符列表。 然后我們詢問用戶密碼的長度,並將其轉換為數字。 之后,我們遍歷長度並向密碼添加一個隨機字符。

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)

代碼 - 您的代碼需要稍作改動

# 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")

您從用戶那里收到的輸入是str類型的,因此您需要將其轉換為int數據類型。

Output


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_length1randomCharacter是兩個 styles。
  • 盡量使您的函數名稱易於理解。 使用generate_random_password不是generatrandompaassword
  • =前后給一些空間。

閱讀一些關於 python PEP 標准的內容,使您的代碼更具可讀性。

暫無
暫無

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

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