0

here's my code

import string
import random
len1 = input("Enter the length of the password you need\n")
ch1 = input("Enter the type\nUpper + Lower ---> 1\nAll Combined ---> 2\n")
if ch1 == '1':
chars = string.ascii_letters
x = ''.join(random.choice(chars) for i in range(len1))
print("Generated Password Based Upon Your Request Is '{0}'".format(x))
elif ch1 == '2':
for i in range(5):
    chars = string.ascii_uppercase + string.ascii_lowercase
    ide = chars + string.digits
    y = ''.join(random.choice(ide) for i in range(len1))
    print("The Generated Password Based Upon Your Request Is '{0}'".format(y))
    print("-----------------")
    print("If Not Generated, You Can Repeat the Process Again Upto {0} times".format(4-i))
    print("-----------------")
    rec = input("Want 2 Repeat?? Press 1; Else 2\n")
    if rec == 1:
        continue
    else:
        break

I am getting x = ''.join(random.choice(chars) for i in range(len1)) TypeError: 'str' object cannot be interpreted as an integer. Pls fix my code and tell me the error.

2 Answers2

1

The result of the input(...) function, is a string - and so your len1 param is a string. To use it in a range function, convert it to an integer. Edit: As chepner mentioned, that will only work if len1 is an int. You can check that - one way to do this is described here:

try:
   x = ''.join(random.choice(chars) for i in range(int(len1)))
except ValueError:
   print('len1 isnt an integer')
A. Abramov
  • 1,823
  • 17
  • 45
0

Why You Are Getting This Error?

Because If You Pass A Data in input it will be string and the range function take int object so you need to convert string to integer

There Are 2 Ways You Can Try

Way1:

x = ''.join(random.choice(chars) for i in range(int(len1)))

Way2 Recommended:

while True:
    try:
        len1 = int(input("Enter the length of the password you need\n"))
        break
    except ValueError:
        print('Please Add Integer Value!')
Hamza Lachi
  • 1,046
  • 7
  • 25