am trying to teach myself Python and am building myself a basic hangman game. I've got a little way but now I'm stuck.
I've tried to put the bulk of the 'counter' for guessing in one function and then reference another function to actually work out whether the guess is correct or not.
So here is my counter function:
def game(generated_word):
hangman_lst = []
guess_num = 0
for i in range(0, len(generated_word)):
hangman_lst.append("__")
print(" ".join(hangman_lst))
while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
guess(l, random_word_stripped, hangman_lst, guess_num)
if "__" not in hangman_lst:
print("**Ta-da!** You're a winner!")
and here is my function to work out whether the guess is correct or not:
def guess(ltr, word, lst, try_num):
upper_ltr = ltr.upper()
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
elif len(upper_ltr) < 1:
print("You didn't enter a letter, try again:")
print(" ".join(lst))
elif upper_ltr in lst:
print("You already guessed that letter, try again:")
print(" ".join(lst))
elif upper_ltr not in word:
print("Sorry, that's incorrect. Try again.")
print(" ".join(lst))
try_num += 1
return try_num
else:
for n in range(0, len(word)):
if word[n] == upper_ltr:
lst[n] = upper_ltr
print("Nice job. That's one. You get a bonus guess.")
print(" ".join(lst))
return lst
So it kind of works, in that the hangman word is updated with the letters as they are guessed. But I can't get the counter to work - guess_num seems to always stay on 0 and so it always loops through this part:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
But, it seems as if lst is returned ok from the guess function, so why isn't try_num?
Cheers!
returndoes, considering that you never useguess's return value.