Reputation: 13
I was trying to build a password generator in Python with this code:
import random
import string
print("Welcome to password generator !")
def password_generator():
lowercase_data = string.ascii_lowercase
uppercase_data = string.ascii_uppercase
numbers = string.digits
symbols = string.punctuation
combined = lowercase_data+uppercase_data+numbers+symbols
lenght= int(input("Enter your password lenght:"))
if lenght == None:
print("please enter your value")
password_generator()
else:
generator = random.sample(combined,lenght)
password = "".join(generator)
print(password)
password_generator()
password_generator()
When my input is blank it shows this error:
ValueError: invalid literal for int() with base 10: ''
Now what should I do with this code??
If my input is blank then I want to continue with the if-statement.
Upvotes: 0
Views: 51
Reputation: 79
You need to catch an exception here. You try to parse a string to int by using int(...)
on a string that can literally contain anything.
In your case, it is empty, so it cannot parse anything to an integer. Your if length == None
afterwards is rather useless, because int()
will not return None
but instead throw an error (see the doc).
You need to catch this error one way or the other, either by surrounding the statement with a try except block or by sanitizing the input (i.e. taking a = input("Enter your pw length:")
and then checking if it only contains digits before you call int(a)
Upvotes: 0
Reputation: 3672
try:
lenght = int(input("Enter your password lenght:"))
except ValueError:
lenght = None
if lenght is None:
...
Trying to convert a non number value to an int generates a ValueError - as you've seen. If that happens, set lenght
to None, and carry on.
Upvotes: 1