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

Python中Matplotlib使用报错:UnboundLocalError问题求助

分析错误原因

咱们先拆解一下你遇到的UnboundLocalError问题:

  • 当你输入的百分比总和超过100时,代码进入if分支,先递归调用getTotal(),接着执行del values。
  • 等递归的getTotal()执行完毕(比如用户这次输入正确了),程序会回到原来的函数调用栈,继续执行后面的plt.pie(values, labels=slices)。但这时候原来的values已经被你del删掉了,变量不存在了,自然就抛出了“变量未定义就引用”的错误。
  • 还有个隐藏问题:就算你没删values,递归调用后原来的函数还是会继续执行绘图代码,这完全不是你想要的——你肯定希望输入错误时,重新输入后只执行一次绘图,而不是原来的函数还继续跑一遍。
修复方案

我给你调整两处关键地方,就能解决问题:

  1. 删掉del values:这行代码完全多余,反而会破坏当前函数的变量环境,直接去掉就行。
  2. 递归调用后加return:进入错误分支递归调用getTotal()后,立刻用return终止当前函数的执行,这样就不会回到原来的函数继续执行绘图代码了。

另外,如果你想更健壮一点,用循环代替递归会更稳妥(避免用户多次输入错误导致栈溢出),我也会给你一个循环版本的代码。

修正后的递归版本代码

import matplotlib.pyplot as plt

def main(): 
    getTotal()

def getTotal(): 
    BTC = int(input('How much would you like to allocate to BTC as a percentage: ')) 
    ETH = int(input('How much would you like to allocate to ETH as a percentage: ')) 
    LTC = int(input('How much would you like to allocate to LTC as a percentage: ')) 
    values = [BTC, ETH, LTC] 
    
    if BTC + ETH + LTC > 100: 
        print('That was too much, try again') 
        getTotal()
        return  # 这里加return,终止当前函数执行
    
    # 把标签换成币种名称,比显示数值更直观
    labels = ['BTC', 'ETH', 'LTC']
    plt.pie(values, labels=labels) 
    plt.title('Crypto Allocations') 
    plt.show()

main()

更健壮的循环版本(推荐)

递归虽然简单,但如果用户多次输入错误,可能会触发递归深度限制。用循环的话逻辑更清晰,也更稳定:

import matplotlib.pyplot as plt

def main(): 
    getTotal()

def getTotal(): 
    while True:
        BTC = int(input('How much would you like to allocate to BTC as a percentage: ')) 
        ETH = int(input('How much would you like to allocate to ETH as a percentage: ')) 
        LTC = int(input('How much would you like to allocate to LTC as a percentage: ')) 
        values = [BTC, ETH, LTC] 
        
        if BTC + ETH + LTC > 100: 
            print('That was too much, try again') 
            continue  # 回到循环开头,重新输入
        
        labels = ['BTC', 'ETH', 'LTC']
        plt.pie(values, labels=labels) 
        plt.title('Crypto Allocations') 
        plt.show()
        break  # 绘图完成后退出循环

main()

内容的提问来源于stack exchange,提问作者Liam O'Toole

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:41:30