【问题标题】:How do I begin the process of generating the user another password?如何开始为用户生成另一个密码的过程?
【发布时间】:2022-01-14 06:56:58
【问题描述】:

我是 Python 新手(2 周),课外一直在研究随机密码生成器。 我已经制作了密码生成器;但是,我不确定如何开始为用户生成另一个密码的过程。到目前为止,我已经尝试过创建一个循环,但很快就迷路了。关于我做错了什么,我最好的猜测是我只是不太了解循环,而创建循环将解决我的问题。

# This greets the user
print('Hello, Welcome to this random password generator')

# This asks the user for the length of the password
length = int(input('\nEnter the length of the password you would like to generate: '))

# This defines data for the string module
lower = string.ascii_lowercase
upper = string.ascii_uppercase
number = string.digits

# This combines the data
all = lower + upper + number

# This allows us to randomize the data collected
temp = random.sample(all, length)

# This generates the password
password = "".join(temp)

# This will generate a password of up to 94 characters
print(password)

# This prompts the user to generate another password
next_generation = input("Would you like to generate another password? (yes/no): ")

【问题讨论】:

  • 请不要将代码作为图片发布,将代码复制并粘贴到帖子本身中。
  • 刚刚知道怎么做,谢谢你的提示!
  • 目前还不清楚您想在代码中的何处或如何使用循环。但是,使用预制模块可以轻松生成密码。 this 有帮助吗?
  • @Lucas 感谢您的帮助!我不认为你可以做得更简单。我想我还有很多东西要学。至于循环,我不确定它是否是最好的做法。我只是想在打印初始密码后为用户生成另一个密码。

标签: python loops


【解决方案1】:
import random
import string

while True:
    length = int(input("Enter password length: "))

    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    number = string.digits

    all = lower+upper+number
    temp = random.sample(all,length)
    password = ''.join(temp)
    print(password)

    # **** This block asks user whether to create another password ****
    # If Yes, code loops back to the beginning and does it again
    # If No, code stops.
    another = input("Generate another password? Y/N: ").capitalize().strip()
    if another == 'Y':
        another = True
        continue
    else:
        break

【讨论】:

    【解决方案2】:

    您确实需要使用循环并将数据存储在数组中或在循环中打印。这篇文章可能会有所帮助,因为它解释了: How to use loops to keep program running

    我假设您希望您的程序每次都不断要求新密码,并且密码的数量不固定。否则你会使用for loop

    【讨论】:

    • 谢谢!我一定会阅读那篇文章。
    猜你喜欢
    • 2019-04-13
    • 2016-05-20
    • 2010-10-22
    • 2011-10-06
    • 2019-04-22
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多