Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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 使用while和if-else循环的简单刽子手游戏无法正确迭代_Python_If Statement_While Loop - Fatal编程技术网

Python 使用while和if-else循环的简单刽子手游戏无法正确迭代

Python 使用while和if-else循环的简单刽子手游戏无法正确迭代,python,if-statement,while-loop,Python,If Statement,While Loop,我正在尝试使用简单的while循环和if-else语句设计一个hungman游戏 游戏规则: 1.从单词列表中选择随机单词 2.当选择单词并要求用户提供他/她的第一猜测时,会通知用户 3.如果用户的猜测是正确的,则该字母是控制台,并通知用户剩余的字母数 用户将只获得5条生命来玩游戏 1.import random 2.import string 3.def hungman(): 4.words = ["dog", "monkey", "k

我正在尝试使用简单的while循环和if-else语句设计一个hungman游戏

游戏规则:

1.从单词列表中选择随机单词

2.当选择单词并要求用户提供他/她的第一猜测时,会通知用户

3.如果用户的猜测是正确的,则该字母是控制台,并通知用户剩余的字母数

  • 用户将只获得5条生命来玩游戏

     1.import random
     2.import string
     3.def hungman():
     4.words = ["dog", "monkey", "key", "money", "honey"]
     5.used_letters = []
     6.word = words[random.randrange(len(words))]
     7.lives=5
     8.while len(word) > 0 and lives > 0:
         9.guess = input("Please guess the letter: ")
         10.if 'guess' in word:
            11.print(guess, " is a correct guess")
            12.used_letters.appened(guess)
            13.if used_letters.len == word.len:
                14.print("Congratulation, You have guessed the correct letter: ",word)      
            15.else:
                16.remaining_letters =  word.len - used_letters.len
                17.print("You have", remaining_letters, "left")
    
    
          18.else:
          19.lives = lives - 1
          20.if lives == 0:
              21.print("Sorry! you don't have more lives to continue the game")
              22.print("Correct word is: ", word)
              23.break
          24.else:
              25.print("You have", lives , " left")
    
     26.hungman()
    
  • 程序应请求用户输入,该输入将存储在
    guess
    变量中。如果用户给出的字母是word字符串中的一个字母,则代码会提示给定的输入是正确的,并将该字母附加到used_letters列表中。否则,它会显示用户输入错误时剩余字母的长度。此外,如果用户未能正确猜出字母,他或她也将失去1条生命

    然而,根据我在第8行的while循环之后的代码,尽管我提供了正确的字母作为用户输入,但控制转到第18行。第10至17行完全废弃。我找不到这种性质的原因

    请在这方面帮助我


    谢谢

    您的代码中有几个问题。 您提到的是因为第10行中有引号。应该是

    if guess in word:
    
    在第12行你有一个打字错误

    used_letters.append(guess)
    
    要获取列表的长度,应使用函数len(),例如

    最后,如果答案正确,就退出循环。你应该使用

    while len(word) > len(used_letters) and lives > 0:
    

    如果在word中猜测
    -无撇号:您当前的情况永远不会为真。不要在代码段中添加行号,这会使复制和运行代码变得困难。
    while len(word) > len(used_letters) and lives > 0: