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

Python如何跨函数调用变量 解决中缀转后缀代码报错问题

报错原因

Python默认函数内部定义的变量为局部变量,仅在函数内部生效。你在variables()函数中定义的OPERATORS、PRIORITY都是局部变量,即使你在formula1中调用了variables(),这两个变量也无法被formula1直接访问,因此抛出变量未定义的报错。

修复方案

最规范的修改方式是调整variables()函数,将配置值作为返回值返回,在formula1中调用时接收返回值即可。同时你原代码还有两处逻辑缩进错误需要修正,否则即使解决变量问题也无法得到正确的后缀表达式:

  • 运算符入栈的stack.append(ch)原缩进在优先级判断的while循环内部,需调整到循环外部
  • 遍历完所有字符后清空栈的while循环、return语句原缩进在for循环内部,需调整到for循环外部

完整可运行代码

try:                    
    def variables():
        OPERATORS = set(['+', '-', '*', '/', '(', ')', '^']) 
        PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3}
        return OPERATORS, PRIORITY

    def formula1(expression):
        OPERATORS, PRIORITY = variables()
        stack = []
        output = ''
        for ch in expression:
            if ch not in OPERATORS:
                output += ch
            elif ch == '(': 
                stack.append('(')
            elif ch == ')':   
                while stack and stack[-1]!= '(':    
                    output += stack.pop() 
                stack.pop() 
            else:   
                while stack and stack[-1]!='(' and PRIORITY[ch] <= PRIORITY[stack[-1]]:
                    output += stack.pop()
                stack.append(ch)
        # 遍历结束后清空栈内剩余运算符
        while stack:
            output += stack.pop()
        return output
    
    expression = input('Enter infix expression: ')
    print('infix expression: ', expression)
    print('postfix expression: ', formula1(expression))
except Exception as e:
    print(e)

测试效果

输入(a+b)后,输出结果为:

Enter infix expression: (a+b)
infix expression:  (a+b)
postfix expression:  ab+

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:06:03