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
🌐
GitHub
gist.github.com › garrettdreyfus › 8153571
Dead simple python function for getting a yes or no answer. · GitHub
def query_yes_no(question, default='no'): if default is None: prompt = " [y/n] " elif default == 'yes': prompt = " [Y/n] " elif default == 'no': prompt = " [y/N] " else: raise ValueError(f"Unknown setting '{default}' for default.") while True: try: resp = input(question + prompt).strip().lower() if default is not None and resp == '': return default == 'yes' else: return distutils.util.strtobool(resp) except ValueError: print("Please respond with 'yes' or 'no' (or 'y' or 'n').\n") ... I propose renaming it to whats_it_gonna_be_boy. ... Lots of great answers here, but prompted for something a little simpler and recursive. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """Simple yes/no function demo.""" def yesno(question): """Simple Yes/No Function.""" prompt = f'{question} ?
🌐
EyeHunts
tutorial.eyehunts.com › home › while loop yes or no python | example code
While loop Yes or No Python | Example code
July 25, 2023 - Use while true with if statement and break statement to create While loop yes or no in Python. Simple if while condition equal to "N" then..
🌐
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 ()

🌐
GitHub
github.com › milaan9 › 03_Python_Flow_Control › blob › main › 006_Python_while_Loop.ipynb
03_Python_Flow_Control/006_Python_while_Loop.ipynb at main · milaan9/03_Python_Flow_Control
">Usually, the control shifts out of the while loop when the while condition is no False. Or you can use various control statements like break, continue, etc to break out of the while loop or break of the particular iteration of the while loop.\n", ... ">You can write an empty while function in Python using the pass statements.
Author   milaan9
🌐
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.

🌐
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
🌐
Coventry University
github.coventry.ac.uk › pages › CUEH › py-quickstart › iteration › while-loops
While Loops - Python for Hackers - Quick Start
# example-3.py # Simplified executable run loop check = True count = 1 while check: if count == 1: print("This program will continue to run until you tell it to stop!") print("Do you want to stop yet?") if count != 1: print("How about now? ") answer = input().lower() stop_commands = ["stop", "exit", "yes", "sure", "get me out of here you filthy mudblood!"] count += 1 if answer in stop_commands: answer = input("Are you sure?
🌐
GitHub
github.com › Akuli › python-tutorial › blob › master › basics › loops.md
python-tutorial/basics/loops.md at master · Akuli/python-tutorial
While loops are really similar to if statements. its_raining = True while its_raining: print("Oh crap, it's raining!") # we'll jump back to the line with the word "while" from here print("It's not raining anymore.")
Author   Akuli
🌐
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.')
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 Overflow
stackoverflow.com › questions › 65293083 › how-to-properly-use-while-not-loops-in-python
How to properly use "while not" loops in python? - Stack Overflow
That's the whole point of while constructs: One uses a variable (or some more complex condition involving varying values, such as not variable) which initially evaluates to True and makes the loop run, but when some condition is met will change its value to False, causing the loop to terminate. ... within the for loop I am referring to (github.com/kiteco/python-youtube-code/blob/master/…), there is another guessed = True which ends the code.
🌐
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!!
🌐
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 yo
🌐
Server Academy
serveracademy.com › blog › python-while-loop-tutorial
Python While Loop Tutorial - Server Academy
November 12, 2024 - 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.
🌐
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

🌐
GitHub
github.com › topics › while-loop
while-loop · GitHub Topics · GitHub
Flow control is the order in which statements or blocks of code are executed at runtime based on a condition. Learn Conditional statements, Iterative statements, and Transfer statements · python-tutorials ipython-notebook jupyter-notebooks python4beginner control-statements for-loop while-loop if-elif-else if-statement nested-if-else-statements python-tutorial-notebook if-else-statements python4everybody nested-for-loops python-tutorial-github python4datascience python-flow-control nested-while-loops break-continue-pass tutor-milaan9
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - Python while loops are compound statements with a header and a code block that runs until a given condition becomes false. The basic syntax of a while loop is shown below: ... In this syntax, condition is an expression that the loop evaluates ...
🌐
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.