Reputation: 15
Beginner here. I am making a simple hangman game that can take up to 6 wrong guesses from the player. As long as they guess right, they can continue playing as many turns as necessary. There is no end behavior, I am just working on getting the input and having the program respond to it properly. My code below:
word_list = ["apple", "hello", "world", "computer"]
def choose_word():
return (random.choice(word_list))
def get_guess():
input("Give me a letter: ")
word = choose_word()
letters_used = list(word)
guess = get_guess()
counter = 0
while counter < 5:
if guess in letters_used:
print("Correct.")
get_guess()
else:
print("wrong")
counter += 1
get_guess()
My train of thought was that by taking the word the computer chose and making it into a list the program could then look at each item in said list and compare it to the input the user gave.
When I run it, it gets input, but it always says wrong, so I am guessing the problem must be in the if statement nested in the while loop.
I have looked at several other hangman games, but I don't see anything similar to what I'm trying to do, or maybe the code is similar but I'm not advanced enough to understand it.
My question is: is there a way to get Python to look at each item inside a list, compare it to a given input, and return a response (be it True/False, etc)?
Upvotes: 1
Views: 43
Reputation: 155418
in
is the correct solution, you were just never giving it valid data to check for. You didn't return from get_guess
, so it always returns None
(thus, guess
was always None
and None
was never in the list
). Similarly, you didn't assign to guess
on subsequent calls, so even if you had returned a value, guess
wouldn't change (it would ask for more guesses, but the input would be discarded and it would always perform the test with the original value). Change the code to (lines with meaningful changes commented):
word_list = ["apple", "hello", "world", "computer"]
def choose_word():
return random.choice(word_list)
def get_guess():
return input("Give me a letter: ") # Must return new guess to caller
word = choose_word()
letters_used = list(word)
guess = get_guess()
counter = 0
while counter < 5:
if guess in letters_used:
print("Correct.")
guess = get_guess() # Must store new guess
else:
print("wrong")
counter += 1
guess = get_guess() # Must store new guess
Upvotes: 4