vendredi 21 octobre 2022

Python random.choice() fails to work in a function

I'm having trouble getting Pythons random.choice to work

Here's the working code:

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("Password Generator")
user_amount_letters = int(input("How many letters would you like in your password?\n")) 
user_amount_symbols = int(input("How many symbols?\n"))
user_amount_numbers = int(input("How many numbers\n"))

characters = []

for i in range(user_amount_letters):
  characters.append(random.choice(letters))
for i in range(user_amount_numbers):
  characters.append(random.choice(numbers))
for i in range(user_amount_symbols):
  characters.append(random.choice(symbols))

random.shuffle(characters)
password = "".join(characters)
print(password)

Here's the same code within a function:

.
.
.
def randomise_user_password(letters, symbols, numbers):
  user_letters = letters
  user_symbols = symbols
  user_numbers = numbers
  characters = []
  
  for i in range(user_letters):
    characters.append(random.choice(letters))
  for i in range(user_numbers):
    characters.append(random.choice(numbers))
  for i in range(user_symbols):
    characters.append(random.choice(symbols))

  random.shuffle(characters)
  password = "".join(characters)
  return password


print(randomise_user_password(user_amount_letters, user_amount_symbols, user_amount_numbers))

The problem seems to be with random.choice, heres the error for reference:

3.8.12/lib/python3.8/password_generator.py", line 288, in choice
    i = self._randbelow(len(seq))
TypeError: object of type 'int' has no len()

I understand what the error is telling me, but have no clue how to resolve it.




Aucun commentaire:

Enregistrer un commentaire