Reputation: 71
I am trying to loop over my hangman project but cannot seem to figure out a way without creating an infinite loop. I want to avoid having to ask for user input in multiple places in my guess function and be able to put it in in one place. I feel like I have all the logic down, I would just need to figure out the looping portion. How can I solve this?
from random import choice
print('Welcome to Hangman!!!, Guess the secret word ')
user_guess = input('What is your first guess at the secret word? ')
org_word = choice(['cat','dog','mug','plate'])
word = set(org_word)
already_guessed = ''
chances = 10
def hang_man():
guess()
check_win()
def guess():
global chances
global correct_letters
global already_guessed
#check for valid input
if len(user_guess) > 1 or user_guess.isnumeric():
print('you entered an invalid input and you lost a guess')
chances -= 1
if chances == 0:
print('Sorry you are out of guesses, You Lost :(')
else:
print(f'you now have {chances} guesses left')
#check if letter was already guessed
elif user_guess in already_guessed:
print('you already entered that letter and you lost a guess')
chances -=1
#incorrect guess
elif user_guess not in word:
print('That guess was not in the word and you lost a guess')
chances -= 1
already_guessed += user_guess
if chances == 0:
print('Sorry you are out of guesses, You Lost :(')
else:
print(f'you now have {chances} guesses left')
#correct guess
elif len(user_guess) == 1 and user_guess in word:
print(f'Great, your guess of {user_guess} was in the word')
word.remove(user_guess)
def check_win():
if len(word) == 0 :
print(f'Congrats, you guessed the correct word {org_word}')
hang_man()
Upvotes: 1
Views: 82
Reputation: 56
You could amend check_win()
to return true when guessed correctly:
def check_win():
if len(word) == 0 :
print(f'Congrats, you guessed the correct word {org_word}')
return True
Then while the word hasn't been guessed:
def hang_man():
while not check_win():
guess()
Edit: Thanks for the spot Pranav Hosangadi.
Upvotes: 1