-1

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.

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • 2
    Loop inside of your login function instead of making a recursive call to login(). – jarmod May 10 '22 at 15:24
  • jarmod - Can you explain exactly what you mean? – Dr.Jegesmedve May 10 '22 at 15:30
  • "Can you explain exactly what you mean?" See where your code says `login()`? You should not do that. That is the recursive call, which is not what you want here. Calling the same function from within itself is just like making any other function call: it will eventually `return`, and control will go back to where it was called from. It's difficult to reason about this logic. Where you wrote that call, you simply wanted to "go back to the beginning" of the code. That is what loops are for. – Karl Knechtel May 10 '22 at 15:37
  • Fundamentally, the problem here is that you are misunderstanding *how calling a function works*. It is **not** a way to "go to" a specific point in the code. It is a way to *ask for a sub-computation to happen, and then use the result*. – Karl Knechtel May 10 '22 at 15:38
  • @KarlKnechtel - Oh, thank you! I indeed misunderstood the function call as you write. That may have been the main mistake that led to the others. – Dr.Jegesmedve May 10 '22 at 15:47

1 Answers1

0

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
whege
  • 1,391
  • 1
  • 5
  • 13