Search code examples
pythonpython-3.xif-statementpasswords

In if-else statement throwing this error "ValueError: invalid literal for int() with base 10: ''


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.


Solution

  • 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.