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

Python猜数字游戏遇UnboundLocalError错误,求问题原因排查

猜数字游戏UnboundLocalError错误解析

问题场景

编写用户与电脑对战的猜数字游戏,电脑通过random模块随机选数,用户输入数字后程序抛出UnboundLocalError,相关代码如下:

import random

player_score = 0
computer_score = 0
restart = 'Y'
stop = 'N'

print("Can you test your luck against the computer?\n Guess the number the computer is thinking, and you win!")
print("---------------------------------------------------------------------------------------------------------------------------------------")

def game():
    player_choice = int(input("Please chose a number: "))
    computer_choice = random.randint(0, 5)
    if player_choice == computer_choice:
        player_score += 1
        print("You win!\nComputer Score: ",computer_score," Player Score: ",player_score)
    elif player_choice != computer_choice:
        computer_choice += 1
        print("Computer wins...\nComputer Score: ",computer_score," Player Score: ",player_score)

错误原因

核心问题:变量作用域冲突

  • player_score和computer_score是定义在函数外部的全局变量,但在game()函数内部尝试修改这些变量时,Python会默认将它们识别为局部变量。
  • 当函数执行到player_score += 1或访问computer_score时,Python找不到这些变量的局部定义,直接抛出UnboundLocalError。

额外笔误

elif分支里写的computer_choice += 1是逻辑错误,你实际想累加的是computer_score(电脑得分),而非电脑随机选择的数字,这会导致分数统计完全失效。

修复方案

方案1:使用global声明全局变量

明确告知函数要操作的是外部全局变量:

import random

player_score = 0
computer_score = 0
restart = 'Y'
stop = 'N'

print("敢和电脑比运气吗?\n猜对电脑想的数字你就赢了!")
print("---------------------------------------------------------------------------------------------------------------------------------------")

def game():
    global player_score, computer_score  # 声明要使用的全局变量
    player_choice = int(input("请选择一个数字:"))
    computer_choice = random.randint(0, 5)
    if player_choice == computer_choice:
        player_score += 1
        print(f"你赢了!\n电脑得分:{computer_score} 你的得分:{player_score}")
    else:
        computer_score += 1  # 修正笔误,累加电脑得分
        print(f"电脑赢了...\n电脑得分:{computer_score} 你的得分:{player_score}")

方案2:通过参数传递+返回值更新分数(更推荐)

避免全局变量带来的副作用,函数接收分数参数并返回更新后的结果:

import random

player_score = 0
computer_score = 0
restart = 'Y'
stop = 'N'

print("敢和电脑比运气吗?\n猜对电脑想的数字你就赢了!")
print("---------------------------------------------------------------------------------------------------------------------------------------")

def game(p_score, c_score):
    player_choice = int(input("请选择一个数字:"))
    computer_choice = random.randint(0, 5)
    if player_choice == computer_choice:
        p_score += 1
        print(f"你赢了!\n电脑得分:{c_score} 你的得分:{p_score}")
    else:
        c_score += 1
        print(f"电脑赢了...\n电脑得分:{c_score} 你的得分:{p_score}")
    return p_score, c_score

# 调用函数时更新分数
player_score, computer_score = game(player_score, computer_score)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:33:21