user9840905
user9840905

Reputation:

Simple Yes or No Loop Python3

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!

Upvotes: 0

Views: 10848

Answers (3)

Olivier Melançon
Olivier Melançon

Reputation: 22294

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

Upvotes: 7

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

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

Upvotes: 0

Kapil
Kapil

Reputation: 459

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

Upvotes: 0

Related Questions