如何使程序要求用户输入长度,并使用输入使密码与用户希望的一样长


#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的代码iv,所以我对它还很陌生

首先,我试着放一个变量,然后向用户询问输入,并将输入插入程序中,然后用它来计算密码的长度,这样可以得到帮助吗?

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

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

输出


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。CCD_ 4和CCD_
  • 尽量使函数名称易于理解。使用generate_random_password而不是generatrandompaassword
  • =之前和之后给它一些空间

阅读一些关于python PEP标准的内容,使您的代码更具可读性。

相关内容

  • 没有找到相关文章

最新更新