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

Python开发Hangman游戏出现Variable referenced before assignment报错怎么解决

Hangman游戏变量计数问题解决方法

问题根源

  • 递归调用wordGuessing()时,每次都会重新执行函数逻辑,函数内部定义的NumberOfMisses每次都会被初始化为0,因此错误计数无法累加
  • 将变量移到全局作用域后报错,是因为Python默认将函数内部被修改的变量识别为局部变量,如果你没有显式声明要使用全局变量,就会在读取阶段抛出「变量引用前未赋值」的错误

方案1:正确使用全局变量

注意:必须严格按照以下步骤修改,否则依然会出现报错或者重置问题

  1. 移除wordGuessing()函数内部的NumberOfMisses = 0初始化语句
  2. 在全局作用域(比如wordList定义之后)添加NumberOfMisses = 0
  3. 在wordGuessing()函数内部第一行添加global NumberOfMisses声明,告知Python该变量使用全局作用域的定义

修改后的函数开头示例:

NumberOfMisses = 0 # 全局初始化

def wordGuessing():
    global NumberOfMisses # 显式声明使用全局变量
    WordOrLetter = input("Do you want to guess the word or a letter? Type 'Word' or 'Letter?'")
    # 剩余原有逻辑保持不变

方案2(更推荐):改用循环替代递归

递归逻辑在这个场景下没有任何优势,反而容易引发变量生命周期、递归深度溢出等问题,改用循环写法逻辑更清晰,也不需要额外处理全局变量:

from time import sleep
from random import choice

wordList = ["Mortgage", "Marsupial", "Bloodshed", "Adventure", "Chronological", "Issue"]

print("Hi! Welcome to the Hangman Python Edition")
chosenWord = choice(wordList)
chosenWordLength = len(chosenWord)
print(chosenWord) # 后续调试完成后可删除
print(f"I have chosen a {str(chosenWordLength)} letter word!")

number_of_misses = 0
while number_of_misses < 6:
    WordOrLetter = input("Do you want to guess the word or a letter? Type 'Word' or 'Letter?'")
    if WordOrLetter == "Word":
        guessingWord = input("Try guessing the word! (First letter is Uppercase, the rest is lowercase)")
        if guessingWord == chosenWord:
            print("Hurray! You got it!")
            break
        else:
            print(f"当前错误次数:{number_of_misses}")
            print("Oops. You didn't guess correctly! ")
            number_of_misses += 1
    elif WordOrLetter == "Letter":
        guess = input("Guess a letter! (Type in lowercase)")
        print(f"You chose the letter {guess}!")
        sleep(1)
        if guess in chosenWord:
            print("You got it right!") 
        else:
            print("Oops! That letter isn't in the word!")
            print(f"当前错误次数:{number_of_misses}")
            number_of_misses += 1

if number_of_misses >= 6:
    print("Oh no! Too many mistake! Game Over!")

内容的提问来源于stack exchange,提问作者Leonardo Alexandre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:06:01