You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  • loop variable type mismatch: The code assigned a string input directly to loop, but the outer while loop checks for a boolean value. Since any non-empty string evaluates to True in Python, the loop never terminated.
  • chances not reset between rounds: The initial chances = 3 was declared outside the outer while loop. 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 == 0 after processing the guess, which meant the check never triggered at the right time (since chances would 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

  1. Reset chances each round: Moved chances = 3 inside the outer while loop so every new word starts with a fresh set of 3 chances.
  2. Fixed loop termination: Replaced the boolean input prompt with a simpler Y/N choice, and explicitly set loop = False when the user selects "N".
  3. 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.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:02:39