BossDog _
BossDog _

Reputation: 105

My while loop only works the second time instead of first

I have a while loop and if you answer the question wrong, it repeats the question, but when I get it right first time it ask again and it works the second time. code:

def signup():
    signup=input("Enter a username: ")
    signup2=input("Enter a password: ")

def login():
    login=input("Enter your username: ")
    login2=input("Enter your password: ")

option=input("Would you like to login or signup?: ")

while option != "signup" or option != "login":

    option=input("Would you like to login or signup?: ")

    if option == "signup":
        signup()
    elif option == "login":
        login()

and the response is:

Would you like to login or signup?: signup
Would you like to login or signup?: signup
Enter a username:

Upvotes: 1

Views: 786

Answers (3)

Barmar
Barmar

Reputation: 781058

You're asking for input a second time inside the loop. You should only do that if the input wasn't one of the valid choices.

You should use and rather than or to test the input. See Why non-equality check of one variable against many values always returns true?

Finally, you should process the input after the loop, since that's when it will contain a valid choice.

option=input("Would you like to login or signup?: ")
while option != "signup" and option != "login":
    option=input("Would you like to login or signup?: ")

if option == "signup":
    signup()
elif option == "login":
    login()

Upvotes: 0

Mathieu
Mathieu

Reputation: 5746

Of course, since you also place the option=input("Would you like to login or signup?: ") outside the loop first. To make this kind of loop, it's better to make an infinite loop and to break on a condition:

while True:

    option=input("Would you like to login or signup?: ")

    if option == "signup":
        signup()
        break
    elif option == "login":
        login()
        break

Upvotes: 0

chepner
chepner

Reputation: 531175

Your condition is incorrect. If option does equal one or the other, the other comparison is guaranteed to be true. You want to use and, not or

while option != "signup" and option != "login":

or by De Morgan's laws

while not (option == "signup" or option == "login"):

The best solution, though, is to use an "infinite" loop with an explicit break statement, so that you only need to write the call to input once.

while True:

    option=input("Would you like to login or signup?: ")

    if option == "signup" or option == "login":
        break


if option == "signup":
    signup()
elif option == "login":
    login()

Upvotes: 1

Related Questions