Search code examples
pythonrandomtypesmoduletraceback

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!


Solution

  • Your logic is fine only error you did is named the same list of numbers as the local variable for the iterator in for loop

       for **numbers** in range(0,(nr_numbers)):
          numb.append(random.choice(*numbers*))
    

    Simplest solution is just to change variable name in for loop since you are not using it anyway. Example:

    for i in range(0,(nr_numbers)):
      numb.append(random.choice(numbers))
    

    EDIT

    A little bit of clarification. In your example every time you call numb.append it tries to take random.choice from the local variable numbers instead of the global variable numbers. Here is a helpful link to help you understand if you do not already know what local and global variables are.