Simple Yes or No Loop Python3

Question:

So I am pretty new to python but am having some trouble creating a basic Yes or No input. I want to be able to do something if the user says yes, do something else if the user says no, and repeat the question if the user inputs something that isn’t yes or no. Here is my code :

def yes_or_no():
    YesNo = input("Yes or No?")
    YesNo = YesNo.lower()
    if(YesNo == "yes"):
        return 1
    elif(YesNo == "no"):
        return 0
    else:
        return yes_or_no()

yes_or_no()

if(yes_or_no() == 1):
    print("You said yeah!")
elif(yes_or_no() == 0):
    print("You said nah!")

In theory this should work but I keep getting a glitch. Whenever I enter yes or no the first time, it always repeats the question. It works fine the second time. Please let me know what I am doing wrong. Thanks!

Asked By: user9840905

||

Answers:

You are first calling yes_or_no, which outputs a value but you throw it away and are calling the function again instead of testing on the output of the first call.

Try storing the output in a variable.

# Store the output in a variable
answer = yes_or_no()

# Conditional on the stored value
if answer == 1:
    print("You said yeah!")

else:
    print("You said nah!")

Side notes

It is considered bad practice to use capitalized names for variables, those should be reserved for classes.

Also, a user-prompt loop is better implemented with a while-loop to avoid adding a frame to your call-stack every time the user enters a wrong input. This is unless you use an interpreter which implements tail-call optimization, which cPython does not.

Here is what an improved version of your function could look like.

def yes_or_no():
    while True:
        answer =  input("Yes or No?").lower()

        if answer == "yes":
            return 1

        elif answer == "no":
            return 0
Answered By: Olivier Melançon

You can use break and continue statements like this:

def yes_or_no():
    YesNo = input("Yes or No?")
    YesNo = YesNo.lower()
    if(YesNo == "yes"):
        return 1
    elif(YesNo == "no"):
        return 0
    else:
        return -1

while(True):
    inp = yes_or_no()
    if(inp == -1):
        continue
    elif(inp == 1):
        print("You said yeah!")
    elif(inp == 0):
        print("You said nah!")
    break
Answered By: Kapil

we do it just by using while loop

while True:
   a = input("Yes or No : ").lower()
   if a == "yes":
       print("You said yeah!")
       break
   elif a == "no":
       print("You said nah!")
       break
Answered By: anjaneyulubatta505
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.