In: Computer Science
Hello! I'm trying to work on a python lab in my class, and we basically have to make this method
play_interactive
Now for the fun bit. The function play_interactive will take just one argument --- the length of patterns to use as keys in the dictionary --- and will start an interactive game session, reading either '1' or '2' from the player as guesses, using the functions you wrote above and producing output as shown in the sample game session at the beginning of this writeup. If the player types in any other input (besides '1' or '2'), the game should terminate.
Hint: the input function can be used to read input from the user as a string.
My code so far looks like this, I have the basic loop down and
working, but my guesses list to retain the guesses for this method
isn't updating
def play_interactive(pattern_length=4):
while True:
x = input()
intX = int(x)
guesses = ([])
if(intX == 1 or intX == 2):
guesses.append(intX)
print(len(guesses))
else:
print("Finished")
break
Any help would be appreciated! Thank you so much
Error in your code was you were declaring the list inside while loop so every time loop runs, list got initialized and you are getting only one item in the list. Initialize the list before while loop, it will work.
Please use below modified code:
def play_interactive(pattern_length=4):
guesses = ([]) #initialize the list outside of while loop
while True:
x = input()
intX = int(x)
if(intX == 1 or intX == 2):
guesses.append(intX)
#below line you can remove, this is just for understanding and
showing the output
print("length of the list is " )
print(len(guesses)) #print the length of the list
else:
print("Finished") #if input is not 1 or 2, print finish and
exit
break
play_interactive() #driver call to the function
output:
Please rate your answer. Thanks