无法停止Python中的函数

2024-05-29 01:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我对我创建的函数有问题,它不会停止,有人能建议我做错了什么吗?你知道吗

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

Tags: thetoyougameinputrawhaverandom
1条回答
网友
1楼 · 发布于 2024-05-29 01:58:28

请求猜测的输入需要在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

这样玩家就可以看到正确字母的顺序。你知道吗

相关问题 更多 >

    热门问题