首页 > 解决方案 > 如何修复“Python 中的 While 循环”在我的代码中不起作用

问题描述

我是 python 的新手,正在尝试学习一些基础知识,我尝试开发一个小型 HANGMAN 游戏。我坚持使用 while 循环格式,除了 HANGMAN 列表中的零索引元素外,它在结果中没有显示任何内容。

import random
HANGMAN = (
"""
-----
|    |
|
|
|
|
|
|
|
|
|
|
-------
"""
  ,
"""
-----
|   |
|   0
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|   |
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|\
|
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|\
|  /
|
|
|
|
|
|
|
------
"""
  ,
"""
-----
|   |
|   0 
|  /|\
|  / \
|
|
|
|
|
|
|
------
""")
print(HANGMAN[0])

play_again = True

while play_again:

         words_list = ['abruptly', 'absurd', 'abyss', 'affix', 'askew', 'avenue', 'awkward', 'axiom', 'azure', 'bagpipes'
                                                                                                              'banjo',
                      'beekeeper',
                      'bikini',
                      'blitz',
                      'blizzard',
                      'boggle',
                      'bookworm',
                      'boxcar',
                      'boxful',
                      'buckaroo',
                      'buffalo',
                      'buffoon',
                      'buxom',
                      'buzzard',
                      'buzzing',
                      'buzzwords',
                      'caliph',
                      'cobweb',
                      'cockiness',
                      'croquet',
                      'crypt',
                      'curacao',
                      'cycle',
                      'daiquiri',
                      'dirndl',
                      'disavow',
                      'dizzying',
                      'duplex',
                      'dearies',
                      'embezzle',
                      'equip',
                      'espionage',
                      'edouard',
                      'exodus',
                      'faking',
                      'glyph',
                      'gnarly',
                      'fixable',
                      'fjord',
                      'flapjack',
                      'flopping',
                      'foxglove',
                      'frazzled',
                      'frizzled',
                      'fuchsia',
                      'funny',
                      'gabby',
                      'galaxy',
                      'galvanize',
                      'gazebo',
                      'gaiter',
                      'gimme',
                      'glowworm',
                      'gossip',
                      'grogginess',
                      'haiku',
                      'haphazard',
                      "stronghold",
                      "stymied",
                      "subway",
                      "swivel",
                      "syndrome",
                      "thriftless",
                      "thumbscrew",
                      "topaz",
                      "transcript",
                      "transgress",
                      "transplant",
                      "triathlon",
                      "twelfth",
                      "twelfths",
                      "unknown",
                      "unworthy",
                      "unzip",
                      "uptown",
                      "vaporize",
                      "vixen",
                      "vodka",
                      "voodoo",
                      "vortex",
                      "voyeurism",
                      "walkway",
                      "waltz",
                      "wave",
                      "wavy",
                      "waxy",
                      "wellspring",
                      "wheezy",
                      "whiskey",
                      "whizzing",
                      "whomever",
                      "wimpy",
                      "witchcraft",
                      "wizard",
                      "woozy",
                      "wristwatch",
                      "wavers",
                      "xylophone",
                      "yachtsman",
                      "yippee",
                      "yoked",
                      "youthful",
                      "yummy",
                      "zephyr",
                      "zigzag",
                      "zigzagging",
                      "zilch",
                      "zipper",
                      "zodiac",
                      "zombie"]
         chossenword = random.choice(words_list).lower()
         guess = None   #player guess input
         guessed_letters = []   #we add all of the users guesses to this list.
         blank_word = []  #repalcing all the letetrs of the chosen word with dashed symbol.
for letter in chossenword:
    blank_word.append('-')
attempt = 6

while attempt > 0:

        if (attempt!= 0 and "-" in blank_word):

            print(('\n You Have () attempts remaining.').format(attempt))

        try:
            guess == str(input('\n please select a letter between A_Z')).lower()
        except :
            print("that's not a valid input , please try again.")
            continue

        else:
            if not guess.isaplha():
                print('that is not a letter, please try again ')
                continue

            elif len(guess) > 1:
             print("that's is more tahn one letetre , please try again")
             continue

            elif guess in guessed_letters:
                print(" you have already guessed that letter , please try again.")
                continue
            else:
                pass

            guessed_letters.append(guess)

            if guess not in chossenword:
                attempts=-1
                print(HANGMAN[(len(HANGMAN)-1)-attempts])

            else :
                SearchMore = True
                startsearchindex == 0
                while searchMore:
                    try :
                        foundAtIndex = chossenword.index(guess, startsearchindex)
                        blank_word[foundAtIndex]= guess
                        startsearchindex = foundAtIndex + 1
                    except :
                        searchMore = False

            print("".join(blank_word))

            if attempts == 0:
                print("sorry. the game is over , The word was" + chossenword)
                print("\nWould you like to play again ?")
                response =input('>').lower()
                if response not in ("yes","y"):
                    play_again = False
                    print("thanks for playing HANGMAN!")
                break

            if "-" not in blank_word :
                print(("\n Congratualtion! {} was the word").format(chossenword))
                print("\n World you like to play again ?")
                response = input('>').lower()
                if response not in ("yes","y"):
                 play_again = False
                 print("thanks for playing HANGMAN!")
                break

在 while 循环中没有任何作用。

标签: pythonpython-3.xpygamepycharm

解决方案


我让您的代码在我的机器上运行,并带有一些语法和空格技巧。总的来说,你在正确的轨道上!while循环只返回循环的第一个元素的原因HANGMAN是因为代码实际上并没有递减attempt值。你在做

attempt=-1

代替

attempt -= 1

这是attempt每次-1迭代的设置。使用-=运算符实际上会减少它。

还有语法不正确的变量声明(您在 Python 中用=, not分配变量==),以及一些不一致的变量用法(attempts而不是attempt, searchmoreandsearchMore等)。

最后,我将单词列表移到了 while 循环之外。您无需在每次 while 循环运行时重新创建该列表。

import random

HANGMAN = ("""| | | | | | | | | | | |""" ,
           """| | | 0 | | | | | | | |""" ,
           """| | | 0 | | | | | | | | |
                    |""" ,
           """| | | 0 |
                   /| | | | | | | | |""" ,
           """| | | 0 |
                   /|\ | | | | | | | |""" ,
           """| | | 0 |
                   /|\ |
                   / | | | | | | |""" ,
           """| | | 0 |
                   /|\ |
                   / \ | | | | | | |"""
          )

words_list = ['abruptly',
                   'absurd',
                   'abyss',
                   'affix',
                   'askew',
                   'avenue',
                   'awkward',
                   'axiom',
                   'azure',
                   'bagpipes',
                   'banjo',
                   'beekeeper',
                   'bikini',
                   'blitz',
                   'blizzard',
                   'boggle',
                   'bookworm',
                   'boxcar',
                   'boxful',
                   'buckaroo',
                   'buffalo',
                   'buffoon',
                   'buxom',
                   'buzzard',
                   'buzzing',
                   'buzzwords',
                   'caliph',
                   'cobweb',
                   'cockiness',
                   'croquet',
                   'crypt',
                   'curacao',
                   'cycle',
                   'daiquiri',
                   'dirndl',
                   'disavow',
                   'dizzying',
                   'duplex',
                   'dearies',
                   'embezzle',
                   'equip',
                   'espionage',
                   'edouard',
                   'exodus',
                   'faking',
                   'glyph',
                   'gnarly',
                   'fixable',
                   'fjord',
                   'flapjack',
                   'flopping',
                   'foxglove',
                   'frazzled',
                   'frizzled',
                   'fuchsia',
                   'funny',
                   'gabby',
                   'galaxy',
                   'galvanize',
                   'gazebo',
                   'gaiter',
                   'gimme',
                   'glowworm',
                   'gossip',
                   'grogginess',
                   'haiku',
                   'haphazard',
                   "stronghold",
                   "stymied",
                   "subway",
                   "swivel",
                   "syndrome",
                   "thriftless",
                   "thumbscrew",
                   "topaz",
                   "transcript",
                   "transgress",
                   "transplant",
                   "triathlon",
                   "twelfth",
                   "twelfths",
                   "unknown",
                   "unworthy",
                   "unzip",
                   "uptown",
                   "vaporize",
                   "vixen",
                   "vodka",
                   "voodoo",
                   "vortex",
                   "voyeurism",
                   "walkway",
                   "waltz",
                   "wave",
                   "wavy",
                   "waxy",
                   "wellspring",
                   "wheezy",
                   "whiskey",
                   "whizzing",
                   "whomever",
                   "wimpy",
                   "witchcraft",
                   "wizard",
                   "woozy",
                   "wristwatch",
                   "wavers",
                   "xylophone",
                   "yachtsman",
                   "yippee",
                   "yoked",
                   "youthful",
                   "yummy",
                   "zephyr",
                   "zigzag",
                   "zigzagging",
                   "zilch",
                   "zipper",
                   "zodiac",
                   "zombie"]

print(HANGMAN[0])
play_again = True

while play_again:

    chosen_word = random.choice(words_list)

    guess = None   #player guess input

    guessed_letters = []   #we add all of the user's guesses to this list.

    blank_word = []  # replacing all the letters of the chosen word with dashed symbol
    for letter in chosen_word: # creating list with dashes instead of letters for the word
        blank_word.append('-')

    attempt = 6 # the number of incorrect attempts a user gets

    while attempt > 0: # while the user still has valid guesses left

        if (attempt!= 0 and "-" in blank_word): # while player can still guess

            print(('\n You Have {} attempts remaining.').format(attempt)) # tell the user how many attempts are left

            try:
                guess = str(input('\n please select a letter between A-Z')).lower() # enter a letter, lowercase it
            except: # will never hit this
                print("that's not a valid input , please try again.")
                continue

            if not guess.isalpha(): # check if the letter is alphabetical
                print('that is not a letter, please try again ')
                continue

            elif len(guess) > 1:
                print("that's is more than one letter , please try again")
                continue

            elif guess in guessed_letters:
                print(" you have already guessed that letter , please try again.")
                continue

            guessed_letters.append(guess) # add guess to guessed_letters

            print("Guessed letters: ",  guessed_letters)

            if guess not in chosen_word: # if the guessed letter isn't in the chosen_word
                attempt -= 1 # reduce # of attempts available
                print(HANGMAN[(len(HANGMAN)-1)-attempt]) # print the element of HANGMAN at (length of HANGMAN - 1) - the # of attempts

            else: # if the guessed letter IS in the chosen_word
                searchMore = True
                startsearchindex = 0
                while searchMore:
                    try :
                        foundAtIndex = chosen_word.index(guess, startsearchindex)
                        blank_word[foundAtIndex]= guess
                        startsearchindex = foundAtIndex + 1
                    except :
                        searchMore = False

            print("".join(blank_word))

        if attempt == 0: # no more attempts
            print("sorry. the game is over , The word was" + chosen_word)
            print("\nWould you like to play again?")
            response =input('>').lower()
            if response not in ("yes","y"):
                play_again = False
                print("thanks for playing HANGMAN!")
                break

        if "-" not in blank_word :
            print(("\n Congratualtion! {} was the word").format(chosen_word))
            print("\n World you like to play again ?")
            response = input('>').lower()
            if response not in ("yes","y"):
                play_again = False
                print("thanks for playing HANGMAN!")
                break

希望这可以帮助!


推荐阅读