我的代码:
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.
答案 0 :(得分:1)
因为div
是一个局部变量,并且是divide
函数的本地变量,所以在其他地方都不知道。您可以尝试:
在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])))
或使用全局变量:
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])))