Skip to content Skip to sidebar Skip to footer

While Loop With Yes/no Input (python)

I am building a script to plot smooth and plot values. However, I am having trouble getting the yes/no function to control the while loop. I am setting the while condition equal to

Solution 1:

Try:

defyes_or_no(question):
    reply = str(input(question+' (y/n): ')).lower().strip()
    if reply[0] == 'y':
        return1elif reply[0] == 'n':
        return0else:
        return yes_or_no("Please Enter (y/n) ")

print("started")
whileTrue:
    # DRAW PLOT HERE;print("See plot....")
    if(yes_or_no('Do you like the plot')):
        breakprint("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): yesdone
$

Solution 2:

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

defbunch_of_math():
    ...

defplotting():
    ...

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

print("start")

whileTrue:
    reply = str(input(question+' (y/n): ')).lower().strip()
    if reply == 'y':
        breakelif reply == 'n':
        breakelse:
        print("please select (y/n) only")
        continueprint("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':
    return1if reply[0] == 'n':
    return0else:
    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.

Solution 3:

defyes_or_no(question):
    whileTrue:
        answer = input(question + ' (y/n): ').lower().strip()
        if answer in ('y', 'yes', 'n', 'no'):
            return answer in ('y', 'yes')
        else:
            print('You must answer yes or no.')

yes_or_no('Do you like the plot?')

Solution 4:

you can't intialize an index of an array.

change reply[0] = 'n' to reply = 'n'

Solution 5:

First error - You never defined reply, so how do you index that string?

whileTrue:
    reply[0] = 'n'# What is reply??

Also break is outside the loop, which should be a SyntaxError.


Second error - You defined a loop, but never changed the value reply in the loop itself. Plus, yes_or_no() is called outside of the loop (but it never breaks the loop, only returns from the function).


You're having some misunderstanding about how functions work. They are separate code blocks, not intended to be nested within your other logic.

defyes_or_no(question):
    whileTrue:
        reply = input(question + ' (y/n): ')).lower().strip()
        if reply.startswith('y'):
            breakprint("started")
yes_or_no('Do you like the plot')
print("done")

Or, probably a more readable version

def yes_or_no(question):
    return input(question + ' (y/n): ')).lower().strip()

print("started")
question = 'Do you like the plot?'
like_plot = yes_or_no(question).startswith('y')
while not like_plot:
    like_plot = yes_or_no(question).startswith('y')
print("done")

Post a Comment for "While Loop With Yes/no Input (python)"