无法在Python中停止功能

时间:2014-01-08 20:58:15

标签: python function

我遇到了我创建的功能问题,它没有停止,任何人都可以建议我做错了什么?

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()

1 个答案:

答案 0 :(得分:1)

您要求猜测的输入需要在game函数内或每次完成时多次触发。

你只是在游戏开始时要求chance。除非玩家立即猜到这个词,否则它不会触发胜利条件。

这样的事情会解决它:

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

额外提示:要按顺序打印所有成功的猜测,这意味着它们在隐藏单词中的顺序,您可以执行以下操作:

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")

输出:

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

这允许玩家查看正确字母的顺序。