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

Python中cal调用calculator函数报num1未定义错误如何解决

错误原因
  • 该错误由Python的局部变量作用域规则导致:函数内部定义的变量默认属于该函数的局部变量,仅能在函数内部访问,无法被其他函数直接读取。
  • 你在cal()函数中定义的num1、num2都是cal的局部变量,calculator()函数默认没有访问这两个变量的权限,因此执行运算时会抛出NameError。
修复方案

只需要调整calculator函数的参数列表,把num1、num2作为入参传入即可,修改后的可运行代码如下:

def calculator(choice, num1, num2):
      if choice=='1':
         print(num1+num2)
      elif choice=='2':
         print(num1-num2)
      elif choice=='3':
          print(num1*num2)
      elif choice=='4':
          # 可选增加除零判断避免后续报错
          if num2 == 0:
              print("除数不能为0")
          else:
              print(num1/num2)
        
def cal():
     print("Select operation.")
     print("1.Add")
     print("2.Subtract")
     print("3.Multiply")
     print("4.Divide")
     choice=input()
     num1= int(input())
     num2= int(input())   
     calculator(choice, num1, num2)

cal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:36:02