Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法停止Python中的函数_Python_Function - Fatal编程技术网

无法停止Python中的函数

无法停止Python中的函数,python,function,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 ha

我对我创建的函数有问题,它不会停止,有人能告诉我我做错了什么吗

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

您要求猜测的输入需要在
游戏
功能内或每次完成时触发多次

在游戏开始时,您只要求获得
机会。除非玩家立即猜出单词,否则不会触发胜利条件

像这样的东西可以解决它:

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

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

您希望它什么时候停止?您使用的是哪个版本的Python?我不确定3.x,但我知道在2.x
return
中有一个语句(不应该有括号)