Nov-06-2019, 09:02 PM
Hi,
I should say from the beginning that I'm very new in Python. I've been following a video tutorial where hangman is being tested. I've got the following code which seems to work for the guy who teaches, but not to me. And I simply don't understand the logic of it to be honest and can't understand how it can actually work.
This is the code:
Is this a mistake that the guy has made?
How could I improve the code, so that the game ends also when I have to guess words whose letters repeat.
Thanks!
I should say from the beginning that I'm very new in Python. I've been following a video tutorial where hangman is being tested. I've got the following code which seems to work for the guy who teaches, but not to me. And I simply don't understand the logic of it to be honest and can't understand how it can actually work.
This is the code:
import random # make a list of words words = [ 'apple', 'banana', 'orange', 'coconut', 'strawberry', 'lime', 'grapefruit', 'lemon', 'kumquat', 'blueberry', 'melon' ] while True: start = input("Press enter/return to start, or enter Q to quit") if start.lower() == 'q': break # pick a random word # choice functions picks a random item out of an iterable secret_word = random.choice(words) print("secret_word is {}".format(secret_word)) bad_guesses = [] good_guesses = [] while len(bad_guesses) < 7 and len(good_guesses) != len(list(secret_word)): # draw spaces # draw guessed letters and strikes for letter in secret_word: if letter in good_guesses: print(letter, end='') else: print('_', end='') print('') print('Strikes: {}/7'.format(len(bad_guesses))) print('') # take a guess guess = input("Guess a letter: ").lower() if len(guess) != 1: print("You can only guess a single letter!") continue elif guess in bad_guesses or guess in good_guesses: print("You've already guessed that letter!") continue elif not guess.isalpha(): print("You can only guess letters!") continue if guess in secret_word: good_guesses.append(guess) if len(good_guesses) == len(list(secret_word)): print("You win! The word was {}".format(secret_word)) break else: bad_guesses.append(guess) else: print("You didn't guess it! My secret word was {}".format(secret_word))What I don't understand is why how this line "if len(good_guesses) == len(list(secret_word)" can actually work. The only situation where I'd assume it can work is when you've only guessed words whose letters don't repeat. So for a word like 'blueberry' it won't work.
Is this a mistake that the guy has made?
How could I improve the code, so that the game ends also when I have to guess words whose letters repeat.
Thanks!