问题
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 "N" and waiting for the user to say they like the plotting (input of Y) before exiting.
I am getting a "NameError: name 'reply' is not defined."
import matplotlib.pyplot as plt
import numpy
while True:
reply[0] = 'n'
def yes_or_no(question):
reply = str(input(question+' (y/n): ')).lower().strip()
if reply[0] == 'y':
return 1
if reply[0] == 'n':
return 0
else:
return yes_or_no("Please Enter (y/n) ")
# a bunch of math
# plots for the user
yes_or_no('Do you like the plot')
break
print("done")
When I adjusted reply[0] to reply the program hangs (see below)
print("started")
while True:
reply = 'n'
def yes_or_no(question):
reply = str(input(question+' (y/n): ')).lower().strip()
if reply[0] == 'y':
return 1
if reply[0] == 'n':
return 0
else:
return yes_or_no("Please Enter (y/n) ")
yes_or_no('Do you like the plot')
print("done")
回答1:
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:
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.
回答3:
def yes_or_no(question):
while True:
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?')
回答4:
you can't intialize an index of an array.
change reply[0] = 'n'
to reply = 'n'
回答5:
First error - You never defined reply
, so how do you index that string?
while True:
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 return
s 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.
def yes_or_no(question):
while True:
reply = input(question + ' (y/n): ')).lower().strip()
if reply.startswith('y'):
break
print("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")
来源:https://stackoverflow.com/questions/47735267/while-loop-with-yes-no-input-python