简体   繁体   中英

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

For my assignment i have to create a password generator using python. it has to ask the user how many characters long they want the password, then it has to create it by using random.randint and prints it out as a string. how do i get the user input to multiply the random.randint bit the number of times they've asked for??

this is what i have so far...........

# 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()

This is very nearly there...

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

Change to a list-comp to build a single list of n items, eg:

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

However, it's easier to use choice then generate an index into the list - then do as you're doing now but repeated...

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM