Search code examples
pythonpython-3.xfunction

How can I call a function within a login() function - python3


I have a login function already which I would like to use in the code to call other functions.

def login():
    while True:
        loginUser = input("Username: ")
        loginPass = getpass.getpass()
        for user_info in users:
            if loginUser == user_info[0] and loginPass == user_info[1]:
                print("Success\n")
                return
        else:
            print("Wrong username or password\n")

Is there a way so that after it prints 'Success' I can call a function without putting it IN the login() function or just rewriting out the entire block of code again for example

login()
if login() is successful then function()
else print wrong username

rather than just adding the whole function to another function or adding the function under the success part.


Solution

  • Instead of a simple return, you can return True if success, and return False if not

    def login():
        while True:
            loginUser = input("Username: ")
            loginPass = getpass.getpass()
            for user_info in users:
                if loginUser == user_info[0] and loginPass == user_info[1]:
                    print("Success\n")
                    return True
            else:
                print("Wrong username or password\n")
                return False
    

    Then using it:

    if login():
        success_function()