Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any ways to save a value from a function which runs several times?

Well, I’m a relative beginner in Python and I wanted to make a simple login function, but I ran into a problem.

def login():
    loginTries = 0
    loginName = str(input("\nPlease enter your username: "))
    loginPassword = str(input("Please enter your password: "))
    if loginName not in loginNames or loginPassword != realLoginPassword:
        print("\nOops! You typed something wrong. Try again!")
        loginTries += 1
    
    while loginTries < 4:
        login()
    else:
        register()
    return

I had planned to redirect to another (register) function after three unsuccessful attempts, but the problem is that I can’t count how many times the function has been repeated, because the values entered are reset each time it is repeated. I pictured it as shown above, but as I wrote before, it does not save the value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The simplest approach is probably to create a separate function to handle attempts. You’d have to adjust your login function a bit to return the expected values, but you could do:

def handle_login():
    login_attempts = 0
    while login_attempts < 3:
        success = login()
        if success == True:
            break
        else:
            login_attempts += 1
    if success == True:
        # redirect to login
    else:
        # redirect to register
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading