簡體   English   中英

我如何從列表中隨機選擇用戶要求在 python 中使用輸入的次數?

[英]how do i randomly pick characters out of a list the amount of times the user asks for using input in python?

對於我的作業,我必須使用 python 創建一個密碼生成器。 它必須詢問用戶他們想要密碼的長度,然后它必須使用 random.randint 創建它並將其作為字符串打印出來。 我如何讓用戶輸入將 random.randint 位乘以他們要求的次數?

這就是我迄今為止所擁有的......

# imports modules
import random, time

# defines welcome function
def welcome():
    print('Welcome to the password generator!')
    time.sleep(2)
    print('This program will generate random passwords.')

# create a list
character_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']

# defines enter number function which asks the user to enter a number
def password_gen():
    i = 'Nothing yet'
    while i.isdigit() == False:

        i = input()
        if i.isdigit() == False:
            print('Please enter a number\n')

    return int(i)

for x in range(0,5):
    rc = character_list[random.randint(0,62)]
    print (rc)

# calls functions and runs the program
welcome()
print('Please press enter...')
password_gen()

這幾乎在那...

for x in range(0,5):
    rc = character_list[random.randint(0,62)]
    print (rc)

更改為list-comp以構建n項目的單個列表,例如:

rc = [character_list[random.randint(0,62)] for _ in xrange(5)]

但是,使用choice然后在列表中生成索引會更容易-然后像現在一樣操作,但是重復...

from random import choice
from string import ascii_letters, digits

chars = ascii_letters + digits
# replace 10 with how many....
passwd = ''.join(choice(chars) for _ in xrange(10))
# create a list
character_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']

import random
pas = list() # random password

number = input() # 8
number = int(number) if number.isdigit() else 0

while(number):
    pas.append(random.choice(character_list))
    number -= nu

result = "".join(pas)
print(result)
# 'jjyMQPuK'

暫無
暫無

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

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