Home > Enterprise >  TypeError when using random.sample() in python
TypeError when using random.sample() in python

Time:11-14

I'm making a password generator and getting a strange error when I try to run the code.

I created a list with characters and I want the code to sort all the elements in that list and print them with a defined range. But when I try to run that code I get a TypeError saying " '<=' not supported between instances of 'int' and 'type'" but I don't know how to solve this, can someone help me?

This is my code:

import random

charaters = ["1","2","3","4","5","6","7","8","9","0", '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', "!", "@", "?","#", "$", "*"]

def Randomize():


    while True:

        
        user_input = int(input("Select the password range (1-50): "))

        while user_input not in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]:

            print("Please select a valid number between 1 and 50")
            user_input = int(input("Select the password range (1-50): "))

        

       
        password = random.sample(charaters, range)
        

        print(password)

        

CodePudding user response:

Please replace range argument in the random.sample function with user_input. Also modified the while condition to check the user_input in a simpler way.

import random

charaters = ["1","2","3","4","5","6","7","8","9","0", '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', "!", "@", "?","#", "$", "*"]

def Randomize():


    while True:

        
        user_input = int(input("Select the password range (1-50): "))

        while user_input < 1 or user_input > 50:

            print("Please select a valid number between 1 and 50")
            user_input = int(input("Select the password range (1-50): "))

        password = random.sample(charaters, user_input)

        print(password)

Randomize()
  • Related