如何让程序要求用户输入长度,并使用输入来生成密码,只要用户愿意

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

这不会让我 post 出于某种原因什么是评论

这是我几天前开始 python 编写的代码,所以我对它还很陌生

首先我尝试输入一个变量,而不是询问用户输入并将输入插入程序并使用它来查找密码应该多长的长度可以获得这方面的帮助吗?

代码 - 您的代码需要稍作改动

# 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 数据类型。

输出


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

建议:

  • 坚持使用 _ 或驼峰式大小写。 pass_length1randomCharacter 是两种风格。
  • 尽量让您的函数名称易于理解。使用 generate_random_password 而不是 generatrandompaassword
  • 前后给space一些给=

Read a bit about python PEP standards to make your code more readable.

我re-wrote你的代码。 您可以阅读评论以了解发生了什么。 本质上,我们有一个将在密码中使用的字符列表。 然后我们询问用户密码的长度,并将其转换为数字。 之后,我们遍历长度并在密码中添加一个随机字符。

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)