-1

i wrote a simple password generator but am having trouble with the inputs.

when running password(10) for example, it runs perfectly but when i request for input, it doesn't seem to register the input as an integer.

any advice?

import random
def password(x):
    pw = str()
    characters = "abcdefghijklmnopqratuvwxyz" + "0123456789" + "!@#$%^&*"
    for i in range(x):
        pw = pw + random.choice(characters)
    return pw

x1 = input("How many characters would you like your password to have? ")

while x1 != int():
    print("Please key in an Integer")
    x1 = input("How many characters would you like your password to have? ")

password(x1)
QYK
  • 1

2 Answers2

1

input() will always return a string, even if it's a string of a number.

You'll need to convert it to an int with the int() function. The code below also catches when the input can't be converted to an int. We wrap it in a while loop so as long as the user doesn't input a str that can be converted to an int it keeps asking.

valid = False
while not valid:
    try:
        x1 = int(x1)
        valid = True
    except ValueError:
        print('not an int')

Also trying to see if something is an int with the statement x1 == int() isn't the right way to do it. int() will just return 0. Instead use isinstance() like this:

if isinstance(your_var, int):
    <your code>

Of course, that's irrelevant because of the fact that input() will always return a string.

Mattwmaster58
  • 2,266
  • 3
  • 23
  • 36
0

In python 3 input() returns a string like python 2's raw_input() to read integers just do int(input('some question'))

Mukundan314
  • 115
  • 2
  • 5