[英]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.