I’m trying to get the user to put in a specific word.
my code:
import os
os.system("clear")
def get_answer():
print "\nWould you like to 'hit', 'stick', 'double' down or 'split'?"
x = raw_input('> ')
answers = ['hit', 'stick', 'double', 'split']
y = [i for i in answers if i in x]
if y == []:
get_answer()
print y
# exit(0)
return y
def foo():
a = get_answer()
print a
foo()
here’s my output if I answer ‘hit’ the first time;
Would you like to 'hit', 'stick', 'double' down or 'split'?
> hit
['hit']
['hit']
here’s my output if I type ‘blah’ the fist time and then ‘hit’:
Would you like to 'hit', 'stick', 'double' down or 'split'?
> blah
Would you like to 'hit', 'stick', 'double' down or 'split'?
> hit
['hit']
[]
[]
I don’t even really know how to research this. Is it a simple syntax error or is there a deeper issue I just don’t understand? I’d love to know how to do this properly.
You want to simply test
if x in answers, which checks to see if the input is one of the elements inanswers.Also, since you are using recursion to get the user’s input, inputting an incorrect value puts another
get_answer()call on the stack. The result is that while the innermostget_answergets valid input, the outerget_answercall(s) continue executing, resulting in the weird output you see.For example, in your second case,
['hit']is generated by the innermost call’sprint y, the first[]is generated by the outer call’sprint y(since the innerget_answerfinishes), and the last[]is generated byprint ainfoo()(since the outerget_answerreturns[]).What you probably want to do instead is either (a) change the
get_answercall toreturn get_answer()so that the innermost call’s value is sent back up the stack, or (b) change theget_answercall to a loop, and break out when you get a good answer.Assuming you’re trying to get the user to input exactly one of the options, here’s how you could structure the code to use a loop instead of recursion: