samedi 11 septembre 2021

Traceback when trying to print a random string

I'm still a beginner, so I'm probably missing something obvious. I'm trying to generate a password with random symbols, letters and numbers and am supposed to only use the functions we already learned (so no advanced stuff).

this is the problematic bit of code:

l=[]
s=[]
numb=[]

for letter in range (0,(nr_letters)):
  l.append(random.choice(letters))
for symbol in range(0,(nr_symbols)):
  s.append(random.choice(symbols))
for numbers in range(0,(nr_numbers)):
  numb.append(random.choice(numbers))

(Info: "nr_letters" (as well as "nr_symbols" etc.) is the input given to us by the user, while "letters" is a list of strings.)

The "for" function works fine with the letters and symbols, but I receive a traceback for "numbers", even though the numbers list is also made up of strings. This is the Traceback:

Traceback (most recent call last):
  File "main.py", line 27, in <module>
    numb.append(random.choice(numbers))
  File "/usr/lib/python3.8/random.py", line 288, in choice
    i = self._randbelow(len(seq))
TypeError: object of type 'int' has no len()

I tried to tell python again, that there are no integrals in my numbers list, so I wrote

numb.append(random.choice(str(numbers)))

But while Python now for some reason understands that the items in that list are strings, it now seems to ignore the "random.choice" bit, because it prints the numbers in order, starting from 0.

What am I doing wrong here? And please no corrections for the rest of the code, as I do want to try to finish the project mainly by myself, because otherwise I won't learn anything. I'm just not understanding why python isn't doing what I think I am telling it to do here. Any help appreciated!




Aucun commentaire:

Enregistrer un commentaire