Search code examples
pythontypeerror

TypeError: object of type 'int' has no len() in python (Password Generator)


I'm trying to create my own random password generator

import random

all = ['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, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, !, ”, $, %, &, *, -, _, +, /, ~']

user_len = input('Enter the length of the password u want: ')

pass_len = len(user_len)
shuffle = random.shuffle(all)

shuffle_len = shuffle(len(pass_len)) 

And whatever I do, the "TypeError: object of type 'int' has no len()" appear and that's error is for the shuffle_len variable


Solution

  • Your all (which is not a good name for a variable as it shadows the built-in function all()) is a list containing one string that has a bunch of commas. (Trying to shuffle a list with one item is not going to do you much good.)

    Chances are you want a list with each possible character as a single string; you can either spell that out ('A', 'B', 'C', ...) or have the list() function split a string up for you.

    all = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!”$%&*-_+/~')
    

    Next, input() returns a string, and so if you take len() off the value, you'd have to enter six to get a 3-letter password, oooooooo to get an 8-letter password, etc.

    Instead, do

    pass_len = int(input('Enter....'))
    

    Next up, random.shuffle() doesn't return anything; it shuffles the input list in-place. shuffle will be None, so trying to call it would fail (if evaluating len(pass_len)) didn't. Even if random.shuffle returned a list, you wouldn't be able to call it. Looks like you want a slice – the pass_len first items, instead.

    You then have a list, but presumably you want to go back to a string, so you'll need to call "".join() on it to join up all of those single characters with nothing in-between.

    All in all, you'll want:

    import random
    
    characters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!”$%&*-_+/~')
    pass_len = int(input('Enter the length of the password u want:'))
    random.shuffle(characters)
    password = "".join(characters[:pass_len])
    print(password)