Python实现Hangman游戏无剩余次数后无限循环问题排查与修复
Fixing Infinite Loop Issue in Python Hangman Game
I built a Hangman game in Python recently, but hit an annoying infinite loop bug once the player used up all their guess chances. Let me break down what went wrong, show the original problematic code, and share the fixed version.
Original Problematic Code
import random import time import sys # Returns a word def get_word(): words = ["apple", "sandwitch", "chance", "winner", "chicken", "dinner"] return random.choice(words) # Checks whether the character is in the word or not def check_character(character, word, newWord): word = list(word) temp = list(newWord) flag = False for i in range(len(word)): if word[i] == character: temp[i] = character flag = True elif str(word[i]).isalpha() == True: pass else: temp[i] = '*' newWord = ''.join(temp) return [newWord, flag] # flag is True if character was in word else False def play(name): chances = 3 points = 0 loop = True print("Welcome {} you have {} chances and your points are {}. ".format(name, chances, points)) while loop: # This loop is getting executed infinitly after no more chances available word = get_word() print("Word is : {}".format(len(word)* '*')) newWord = len(word) * '*' while chances != 0: if '*' in newWord: character = input("Enter a character: ") temp = check_character(character, word, newWord) newWord, flag = temp[0], temp[1] if chances == 0: print("Guess was wrong. No remaining chances .") print("Your score was: {}".format(points)) sys.exit(0) # sys.exit() also not working after all the chances are gone elif flag == False and chances != 0: chances = chances - 1 print("Guess was wrong. Chances remaining are {}".format(chances)) else: print("Word is : {}".format(newWord)) else: print("Hurray!!! you have guessed the word correctly.") points = points + 1 print("Your points: {}".format(points)) print("Your remaining chances: {} ".format(chances)) loop = input("Would you like to continue(True/False only):") break print("Welcome to the Hangman Game!!!! ") time.sleep(1) print("Loading.", end= "") time.sleep(1) print(".", end= "") time.sleep(1) print(".", end= "") time.sleep(1) print(".") name = input("Enter your Name: ") play(name)
Root Causes of the Infinite Loop
After debugging, I found two key issues:
loopvariable type mismatch: The code assigned a string input directly toloop, but the outerwhileloop checks for a boolean value. Since any non-empty string evaluates toTruein Python, the loop never terminated.chancesnot reset between rounds: The initialchances = 3was declared outside the outerwhileloop. Once the player used up all chances, subsequent rounds would immediately skip the inner guess loop and repeat the outer loop indefinitely.- Bonus: Misplaced game-over check: The code tried to check if
chances == 0after processing the guess, which meant the check never triggered at the right time (sincechanceswould only hit 0 after decrementing).
Fixed Code
import random import time import sys def get_word(): words = ["apple", "sandwitch", "chance", "winner", "chicken", "dinner"] return random.choice(words) def check_character(character, word, newWord): word = list(word) temp = list(newWord) flag = False for i in range(len(word)): if word[i] == character: temp[i] = character flag = True elif str(word[i]).isalpha() == True: pass else: temp[i] = '*' newWord = ''.join(temp) return [newWord, flag] def play(name): points = 0 loop = True print("Welcome {} you have 3 chances and your points are {}. ".format(name, points)) while loop: # Reset chances for each new word round chances = 3 word = get_word() print("Word is : {}".format(len(word)* '*')) newWord = len(word) * '*' while chances != 0: if '*' in newWord: character = input("Enter a character: ") temp = check_character(character, word, newWord) newWord, flag = temp[0], temp[1] if flag == False and chances == 1: print("Guess was wrong. No remaining chances .") print("Your score was: {}".format(points)) sys.exit(0) elif flag == False and chances > 0: chances = chances - 1 print("Guess was wrong. Chances remaining are {}".format(chances)) else: print("Word is : {}".format(newWord)) else: print("Hurray!!! you have guessed the word correctly.") points = points + 1 print("Your points: {}".format(points)) print("Your remaining chances: {} ".format(chances)) # Use a more user-friendly prompt and properly set loop status answer = input("Do you wish to continue ? (Y/N)").upper() if answer == "N": loop = False break print("Welcome to the Hangman Game!!!! ") time.sleep(1) print("Loading.", end= "") time.sleep(1) print(".", end= "") time.sleep(1) print(".", end= "") time.sleep(1) print(".") name = input("Enter your Name: ") play(name)
Key Fixes Explained
- Reset chances each round: Moved
chances = 3inside the outerwhile loopso every new word starts with a fresh set of 3 chances. - Fixed loop termination: Replaced the boolean input prompt with a simpler Y/N choice, and explicitly set
loop = Falsewhen the user selects "N". - Corrected game-over logic: Now checks if a wrong guess will use up the last chance before decrementing, ensuring the game-over message triggers correctly and exits the program.
- Removed broken exit call: The original
sys.exit()was placed in a section that never ran; the new check ensures it fires at the right moment.
内容的提问来源于stack exchange,提问作者Abhishek Tripathi
相关产品推荐
相关产品推荐

