Joe Doe
Joe Doe

Reputation: 193

Cannot stop function in Python

I am having problem with function that I have created, it does not stop, can anyone suggest what am I doing wrong?

import random

words = ["monitor", "mouse", "CPU", "keyboard"]

attempts = []

randomWord = random.choice(words)

noChar = len(randomWord)

print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."

def game():    
    guess = raw_input ("Please choose letter")
    attempts.append(guess)
    print (attempts)

    if guess in randomWord: 
        print "You have guessed the letter" 
    else: 
        print "Please try again"
    return()  

chance = raw_input ("Have a guess")

while chance!= randomWord:
    game()

Upvotes: 0

Views: 82

Answers (1)

kylieCatt
kylieCatt

Reputation: 11039

The input where you ask for a guess needs to be triggered more than once either inside the game function or every time it finishes.

You are only asking for chance at the beginning of the game. Unless the player immediately guesses the word it won't trigger the victory condition.

Something like this will fix it:

def game():    
    guess = input ("Please choose letter")
    attempts.append(guess)
    print (attempts)

    if guess in randomWord: 
        print ("You have guessed the letter" )
    else: 
        print ("Please try again")


while True:
    game()
    chance = input ("Have a guess")
    if chance == randomWord:
        print('You win!')
        break

Bonus tip: To print all the succesful guesses in order, meaning in the order they are in in the hidden word you can do something like:

def game():    
    guess = input ("Please choose letter")
    if guess in randomWord:
        success.append(guess)
    attempts.append(guess)
    print (attempts)
    print(sorted(success, key=randomWord.index))
    if guess in randomWord: 
        print ("You have guessed the letter" )
    else: 
        print ("Please try again")

Would output:

Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has 7  letters.
Please choose letterm
[]
['m']
You have guessed the letter
Have a guesst
Please choose lettert
[]
['m', 't']
You have guessed the letter
Have a guess
Please choose lettero
[]
['m', 'o', 't']
You have guessed the letter
Have a guess

This allows the player to see what order the correct letters go in.

Upvotes: 1

Related Questions