为什么代码抛出错误'variable'没有定义

时间:2017-08-26 14:22:00

标签: python

我的代码:

def divide(x,y):

    div = divmod(x,y)
    return div

query = input("Enter numbers separated with a comma to divide: ")
divide(int(query.split(',')[0]),int(query.split(',')[1]))
print(div)

为什么会抛出错误:

NameError: name 'div' is not defined.  

2 个答案:

答案 0 :(得分:1)

因为div是一个局部变量,并且是divide函数的本地变量,所以在其他地方都不知道。您可以尝试:

  1. 在print函数中调用函数:

    def divide(x,y):
      div = divmod(x,y)
      return div
    
    query = input("Enter numbers separated with a comma to divide: ")
    print(divide(int(query.split(',')[0]),int(query.split(',')[1])))
    
  2. 或使用全局变量:

    def divide(x,y):
      div = divmod(x,y)
      return div
    
    query = input("Enter numbers separated with a comma to divide: ")
    div = divide(int(query.split(',')[0]),int(query.split(',')[1]))
    print(div)
    

答案 1 :(得分:0)

因为div是函数divide中的局部变量,并且您尝试将其作为全局变量访问。

该代码应该是:

def divide(x,y):
    div = divmod(x,y)
    return div

query = input("Enter numbers separated with a comma to divide: ")
print(divide(int(query.split(',')[0]),int(query.split(',')[1])))