Skip to content
Advertisement

How to turn a variable iterable?

Is there any way I can turn a variable iterable in a for loop? I am trying to make a password generator and for the for loop I use a variable which is an input number.

for lists in(nr_letters):
    thing_ = letters[stuff]
    thing_ + other_thing

When I try to use a variable in a loop I get 'int' object is not iterable.

Advertisement

Answer

Erm… something like

possible_chars = [ 'a', 'b', 'c', ...]
nr_letters = int(input('enter password length'))
password = ''
for _ in range(nr_letters):
    token = pick_at_random_from(possible_chars, 1)
    password = password + token
return password

Like this?

For the pick at random function you can look at https://docs.python.org/3/library/random.html#random.choice

Following the comments I rewrote and fixed them into something functional

import random
letters = ['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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!") 
nr_letters= int(input("How many letters would you like in your password?n"))
nr_symbols = int(input(f"How many symbols would you like?n")) 
nr_numbers = int(input(f"How many numbers would you like?n"))

#create a list of pairs (list, number of chars)
lists = [ (letters, nr_letters), (symbols, nr_symbols), (numbers, nr_numbers)]
password = '' # this is our building block in which we accumulate the choiches

for collection, size in lists: # iterate through a list
    for _ in range(size): # For how many chars we want from that list
        i = random.randint(0, size) # pick a random index
        token = collection[i] # pick the random item using the index
        password = password + token # add the item to the password

print(password) # show the password

Advertisement