Search code examples
if-statementwhile-loopuser-inputpython-3.5

Python 3 - If Statement repeating user input


def namemc():
    global mcname
    agree = ""
    print("")
    mcname = input("Enter your name... ")
    if mcname == "":
        mcname = "Red"
    mcname = mcname.capitalize()
    print("")
    print("OAK")
    txt("Right!\n"
        "So your name is " + mcname + "!")
    print("")
    while agree != "yes" or "no":
        agree = input("yes / no ")
        if agree == "yes":
            print("")
            return mcname
        elif agree == "no":
            agree = ""
            namemc()
        else:
            print("")
            print("Please type yes or no.")
            print("")

I am trying to create a function that will give users the option to name their character and the option to change their mind if they do not like this name.

To test that everything was working I called a print statement once the function returns.

Everything seems to be working fine if the user accepts the first name they choose.

Enter your name... glitch

OAK
Right!
So your name is Glitch!

yes / no yes

Glitch

However, if the user changes their mind the function calls the user input twice.

Enter your name... 

OAK
Right!
So your name is Red!

yes / no no

Enter your name... glitch

OAK
Right!
So your name is Glitch!

yes / no yes

yes / no yes

Glitch

Have I made a mistake in the coding somewhere?

Thankyou,

Glitch.


Solution

  • You should change:

        elif agree == "no":
            agree = ""
            namemc()
    

    To:

        elif agree == "no":
            agree = ""
            return namemc()
    

    otherwise the while loop continues