Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get my random password generator in Python to work?

I’m in a college class for programming and I have to make a random number generator using Python, but I can never seem to get it to work. I either get an error or nothing gets displayed. Currently the error I’m getting with this version is

line 34, in <module> 
print(rand.randchoice(X) in range(Y))
return seq[self._randbelow(len(seq))]
Type Error: object of type'int' has no len()
import os
import sys
import random as rand   
import string as str

#FUNCTION FOR THE UI
print('Please choose a difficulty level for your new password:')
print('1. Easy')
print('2. Medium')
print('3. Hard')
X = int(len(input('Enter Your Choice Here: ')))
Y = int(len(input('Enter Number of Characters Here: ')))

easy = str.ascii_lowercase
medium = str.ascii_lowercase + str.ascii_uppercase + str.digits
hard = str.ascii_letters + str.ascii_uppercase + str.digits + str.punctuation

if X == '1':
    X = easy
elif X =='2':
    X = medium
elif X == '3':
    X = hard

print(rand.choice(X) in range(Y))

I also tried putting in all of the characters in to the arrays manually. I was hoping for it to get random characters from each list with a length that matches "Y".

The first line of code is line 7, the last line is line 34

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error is occurring because the variable y is an integer representing the length of the input string, rather than the number of characters the user wants in their random string.

import random as rand
import string as string_module

print('Please choose a difficulty level for your new password:')
print('1. Easy')
print('2. Medium')
print('3. Hard')

x_choice = input('Enter Your Choice Here: ')
y_chars = int(input('Enter Number of Characters Here: '))

easy = string_module.ascii_lowercase
medium = string_module.ascii_lowercase + string_module.ascii_uppercase
hard = string_module.ascii_letters + string_module.digits + string_module.punctuation

if x_choice == '1':
    x = easy
elif x_choice == '2':
    x = medium
elif x_choice == '3':
    x = hard
else:
    print("Invalid choice!")

Now, y_chars represents the number of characters the user wants in their random string, which should resolve the TypeError you were encountering.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading