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.
JavaScript
x
4
1
for lists in(nr_letters):
2
thing_ = letters[stuff]
3
thing_ + other_thing
4
When I try to use a variable in a loop I get 'int' object is not iterable
.
Advertisement
Answer
Erm… something like
JavaScript
1
8
1
possible_chars = [ 'a', 'b', 'c', ]
2
nr_letters = int(input('enter password length'))
3
password = ''
4
for _ in range(nr_letters):
5
token = pick_at_random_from(possible_chars, 1)
6
password = password + token
7
return password
8
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
JavaScript
1
23
23
1
import random
2
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']
3
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
4
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
5
6
print("Welcome to the PyPassword Generator!")
7
nr_letters= int(input("How many letters would you like in your password?n"))
8
nr_symbols = int(input(f"How many symbols would you like?n"))
9
nr_numbers = int(input(f"How many numbers would you like?n"))
10
11
#create a list of pairs (list, number of chars)
12
lists = [ (letters, nr_letters), (symbols, nr_symbols), (numbers, nr_numbers)]
13
password = '' # this is our building block in which we accumulate the choiches
14
15
for collection, size in lists: # iterate through a list
16
for _ in range(size): # For how many chars we want from that list
17
i = random.randint(0, size) # pick a random index
18
token = collection[i] # pick the random item using the index
19
password = password + token # add the item to the password
20
21
print(password) # show the password
22
23