This is a simple one:

while True:
    a = input("Enter yes/no to continue")
    if a=="yes":
        gameplay()
        continue
    elif a=="no":
        break
    else:
        print("Enter either yes/no")

Where gameplay function contains the code to be executed

Answer from Aswin Murugesh on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › yes or no for a while loop?
r/learnpython on Reddit: Yes or No for a While Loop?
October 9, 2023 -

(Solved) I'm trying to ask the user if they want to continue by typing in either Y/y for yes or N/n for no. If i type Y twice it sends me to my print(Thank you for playing). What did I do wrong here?

def dmg ():

import random

damage = random.randint(1,12)

longSword(damage)

def longSword(damage):

cont = input("Would you like to attack? (Type Y or y for yes and N or n for N)")

while cont == "y" or "Y":

print('Your longsword hit for', damage, "damage")

cont = input("Would you like to attack again?")

if cont == "n" or "N":

print('Thank you for playing')

break

dmg ()

Discussions

Newbie question - Programming help
I have a task to program a ‘while loop’ that accepts input form the user that is supposed to work like this: If the user types “yes” the game starts, if the user types “no”, they gets a message saying “why are you here then?”, and if they answer something else that is different to “yes” or ... More on discuss.python.org
🌐 discuss.python.org
0
0
October 21, 2022
Using a while loop to ask the user (Y/N) ?
You can stay in the loop until they provide the answer you want and then break when they do. while True: answer = input('y or n: ').lower() if answer in ['y','n']: break More on reddit.com
🌐 r/learnpython
6
4
October 31, 2023
while loop help...

(I'm going to try not to give you the answer, but to push you towards it)

You want the while loop to run over and over again until the user inputs neither yes or no, right? So you'd want to break out of the loop if the answer is yes, break out of the loop if the answer is no, else try again, so you need to set up the condition for exit, for entry, and the logic in between.

As for where you'd put the while loop, you want to put it on the global line, then all your logic indented inside.

More on reddit.com
🌐 r/learnpython
17
9
September 9, 2015
python - Simple Yes or No Loop Python3 - Stack Overflow
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 More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2018
🌐
Nemoquiz
nemoquiz.com › python › python-while-loops
Python While Loops | NemoQuiz
You can use the break keyword to finish a loop. Here is an example: while True: a = input('Continue? (yes or no)') if a == 'no': break print('The infinite loop has been broken.')
🌐
EyeHunts
tutorial.eyehunts.com › home › while loop yes or no python | example code
While loop Yes or No Python | Example code
July 25, 2023 - while True: # your code cont = input("Another one? yes/no > ") while cont.lower() not in ("yes", "no"): cont = input("Another one? yes/no > ") if cont == "no": print("Break") break ... Best to keep the function definition separate from the loop for clarity. Also, otherwise, it will be read in every loop wasting resources. def yes_or_no(question): reply = str(input(question + ' (y/n): ')).lower().strip() if reply[0] == 'y': return 1 elif reply[0] == 'n': return 0 else: return yes_or_no("Please Enter (y/n) ") print("started") while True: # DRAW PLOT HERE; print("See plot....") if yes_or_no('Do you like the plot'): break print("done")
🌐
Python.org
discuss.python.org › python help
Newbie question - Programming help - Python Help - Discussions on Python.org
October 21, 2022 - I have a task to program a ‘while ... this: If the user types “yes” the game starts, if the user types “no”, they gets a message saying “why are you here then?”, and if they answer something else that is different to “yes” or ...
🌐
YouTube
youtube.com › jake pomperada
Do You Want To Continue Yes or No in Python - YouTube
#doyouwanttocontinue #python #programming #coding #machineproblem #pythonprogramming #jakepomperada #computers #freepython #tutorials #webdevelopment #pychar...
Published   March 9, 2022
Views   13K
🌐
Quora
quora.com › I’m-new-to-Python-how-can-I-write-a-yes-no-question
I’m new to Python, how can I write a yes/no question? - Quora
(y/n): ").strip().lower · Continue Reading · To present a yes/no question in Python you need to (1) show the question to the user, (2) read their input, (3) normalize that input, and (4) interpret it as yes or no (with a fallback if unclear).
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › using a while loop to ask the user (y/n) ?
r/learnpython on Reddit: Using a while loop to ask the user (Y/N) ?
October 31, 2023 -

So I have a program that calculates compound interest, and now I need to add a question at the end of my program that asks the user if they would like to run the program again, if they answer with Y or y the program will restart to the beginning, if they answer “N” or “n” the program is over. And if they answer with anything other than y or n it should repeat the question until the user finally enters y or n

What I have so far:

I have my entire program in a while loop and was able to get it to reset while Var == Y or y. But I can’t get it to repeat the question if the user answers with let’s say “q” or “618” or “L”. Does anyone know how to do something like this, please let me know… thank you

🌐
Reddit
reddit.com › r › learnpython › comments › 3k58yk › while_loop_help
r/learnpython - while loop help...
September 9, 2015 -

Hello anyone, I'm trying to write a program that asks the user if he/she wants to play a game. The user has the option of only entering 'yes' or 'no' and if it's anything other than that, the program should enter a while loop that asks the user to "please enter a valid answer of either 'yes' or 'no'. So far I have this:

print("would you like to play a game?")
answer = raw_input()

if answer == "yes":
print("Let's play!!")
elif answer == "no":
print("Ok, another day...")
else:
answer = False

But where to put the while loop??

Update: Ok guys, thanks for your help. I got!

print("would you like to play a game?")

answer = None

while answer != 'yes' or answer != 'no':
answer = raw_input("Please enter yes or no: ")

if answer == "yes":
print("Let's play!!")
else:
print("Ok, another day...")

I was also trying write a program that has a definition. So far I have this

def game(answer):
if answer == 'yes':
print("Ok, let's begin!")
elif answer == 'no':
print("Ok, another time then...")
print("Would you like to play a game?")
answer = input()

while True:
if answer != 'yes' or answer != no:
answer = input("Please enter a valid response ")
continue
else:
break
game(answer)

but I don't know what I'm doing wrong in block 5.

🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-loops-in-python
How to Use Loops in Python
December 11, 2025 - valid_response = False while not valid_response: response = input("Enter 'yes' or 'no': ") if response.lower() == 'yes' or response.lower() == 'no': valid_response = True else: print("Invalid response. Please enter 'yes' or 'no'.") Let's take a look at some advanced uses of loops in Python.
🌐
GitHub
gist.github.com › garrettdreyfus › 8153571
Dead simple python function for getting a yes or no answer. · GitHub
Correct me if I am wrong but this might be OK with the Assigment Expressions (PEP 572) in Python 3.8 · while res:= input("Do you want to save? (Enter y/n)").lower() not in {"y", "n"}: pass ... def getch(): """Read single character from standard input without echo.""" import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch def yes_or_no(question): c = "" print(question + " (Y/N): ", end = "", flush = True) while c not in ("y", "n"): c = getch().lower() return c == 'y' if __name__ == "__main__": if not yes_or_no("Continue?"): print("NO") # ...or echo nothing and just provide newline os._exit(0) else: print("YES")
Top answer
1 of 5
3

Try:

def yes_or_no(question):
    reply = str(input(question+' (y/n): ')).lower().strip()
    if reply[0] == 'y':
        return 1
    elif reply[0] == 'n':
        return 0
    else:
        return yes_or_no("Please Enter (y/n) ")

print("started")
while True:
    # DRAW PLOT HERE;
    print("See plot....")
    if(yes_or_no('Do you like the plot')):
        break
print("done")

Best to keep function definition separate from loop for clarity. Also, otherwise it will be read in every loop wasting resources.

Output:

$ python ynquestion.py 
started
See plot....
Do you like the plot (y/n): n
See plot....
Do you like the plot (y/n): N 
See plot....
Do you like the plot (y/n): NO
See plot....
Do you like the plot (y/n): No
See plot....
Do you like the plot (y/n): no
See plot....
Do you like the plot (y/n): yes
done
$
2 of 5
1

You should definitely look at some tutorials about "how to code" in general. There are several "misconceptions". However, here is a cleaner version:

import matplotlib.pyplot as plt
import numpy

def bunch_of_math():
    ...

def plotting():
    ...

# move this into the loop in case you want to calc and plot
# new stuff every iteration
bunch_of_math()
plotting()

print("start")

while True:
    reply = str(input(question+' (y/n): ')).lower().strip()
    if reply == 'y':
        break
    elif reply == 'n':
        break
    else:
        print("please select (y/n) only")
        continue

print("done")

It is bad style to declare a function inside a loop, especially if you do not need this. Your code would re-create the function at each iteration, which you would only need if you somehow alter your function in each iteration.

reply[0] = 'n' means that you want to access the list or array (a container data structure) reply with the index 0 and write 'n' there. You have not initialized such a container. Additionally, you do not need a container at all, because you do not store each user input. You just care for the most recent answer of you user -> a variable is enough.

if reply[0] == 'y':
    return 1
if reply[0] == 'n':
    return 0
else:
    return yes_or_no("Please Enter (y/n) ")

You have two if conditions after another: Python would check for == 'y' and then always check again for == 'n'. You need to use elif to declare an else-if condition, otherwise you waste resources or ran into unexpected behavior. Additionally, you are never using the return values. The while-loop just exits with a break statement, because it is a loop. Thus, your return statements are pointless.

🌐
Stack Abuse
stackabuse.com › bytes › handling-yes-no-user-input-in-python
Handling Yes/No User Input in Python
August 21, 2023 - If the response is "no" or "n", we print "Exiting..." and break out of the loop. If the response is anything else, we print "Invalid input. Please enter yes/no." and continue with the next iteration of the loop. In this Byte, we've explored how to solicit Yes/No user input in Python. We've also discussed how to accommodate variations of Yes/No responses and how to implement Yes/No user input within a while loop.
🌐
Server Academy
serveracademy.com › blog › python-while-loop-tutorial
Python While Loop Tutorial - Server Academy
Enter 'yes' or 'no': yes You entered: yes · Here’s a simple countdown timer using a while loop. import time countdown = 5 while countdown > 0: print(countdown) countdown -= 1 time.sleep(1) # Pauses for 1 second print("Time's up!") ... This example uses the time.sleep() function to create a 1-second delay between each countdown number. The while loop is a versatile and powerful control structure in Python that can help you manage iterative tasks based on conditions.
🌐
Python Forum
python-forum.io › thread-38568.html
Looping a question until correct feedback is given
October 30, 2022 - I'm writing my first python program as a number guessing game. I am trying to loop a question until a 'yes' or 'no' response is given but am having trouble figuring it out. ''' response = input('Do you want to try a guessing game?: [yes or no]') whi...
🌐
Python.org
discuss.python.org › python help
While true loop, i want to give the user another reply for his second try - Python Help - Discussions on Python.org
September 23, 2023 - In this case, if the user puts 'N' he will get back to the first line, right? if the user puts again 'N', I want to give him another reply for his second retry answer = input ("Stranger: Can you provide us your information ?(Y/N): ") .upper() while True : if answer == “Y” : break if answer == “N”: print ("please reconsider your your answer ") Continue else: print ("bruv, It is a Yes or No question!!
🌐
Codecademy
codecademy.com › forum_questions › 55565e2876b8fe24e6000566
Erroneous logic for question/challenge for Python: Loops 4/19 | Codecademy
July 18, 2015 - But if you notice, the code that’s already loaded into the script.py file UI starts with the initialized user input variable at line 1, outside of the While loop: choice = raw_input('Enjoying the course? (y/n)') while ________: # Fill in the condition (before the colon) choice = raw_input("Sorry, I didn't catch that. Enter again: ") ... Because your program might need a valid answer which is either yes or no so if you enter something else by mistake then it would indeed be desirable to ask again.