Search code examples
pythonvalidationwhile-loop

I am trying to print "ok" but it doesn't seem to work


I am trying to print "ok" but it doesn't seem to work.

Here is my code:

def passvalidation(password):
    if len(password) < 8:
        print('password must be at least 8 characters')
    elif password.isnumeric():
        print("your password must contain at least one letter")
    elif password.isalpha():
        print("your password must contain at least one number")
    else:
        print("your password is correct")


while True:
    password = input("enter your password: ")
    passvalidation(password)


print("ok")

Why isn't "ok" being printed?


Solution

  • The answers haven't really addresses your largest problem. passvalidation should return a value, either True or False, based on whether the password was valid or not.

    def passvalidation(password):
        if len(password) < 8:
            print('password must be at least 8 characters')
        elif password.isnumeric():
            print("your password must contain at least one letter")
        elif password.isalpha():
            print("your password must contain at least one number")
        else:
            print("your password is correct")
            return True
        return False
    
    while True:
        password = input("enter your password: ")
        if passvalidation(password):
            break
    
    print("ok")
    

    As a general rule, a function should serve one purpose. If your function is supposed to validate passwords, then have it DO that, but it shouldn't print anything. It should be up to the caller to decide what to DO with the information. In this case, you could return an error message:

    def passvalidation(password):
        if len(password) < 8:
            return 'password must be at least 8 characters'
        elif password.isnumeric():
            return "your password must contain at least one letter"
        elif password.isalpha():
            return "your password must contain at least one number"
        else:
            return None
    
    while True:
        password = input("enter your password: ")
        err = passvalidation(password)
        if err:
            print(err)
        else:
            break
    
    print("ok")
    

    NOW you can reuse that function in some other program that doesn't have a console at all.