如何在 python 中调用用户定义函数中声明的变量
How to call the variable declared in user defined function in python
每当我用变量定义 python 中的任何函数时,我都无法调用或打印函数中声明的变量的值,因此无法在后续代码行中使用该变量。
如果我能知道我在使用它时哪里错了,那将非常有帮助。
例如创建500个号码列表的代码行如下:
它给出错误:NameError: name 'r1' is not defined
def createlist(r1):
for n in range(1,500):
return np.arange(r1, r1+n, 1)
r1 = 1
print(createlist(r1))
问题是因为缩进。
您正在函数中声明 r1
。它给你错误,因为 print(createlist(r1))
看不到 r1
。所以解决方案是:
import numpy as np
def createlist(r1):
for n in range(1,500):
return np.arange(r1, r1+n, 1)
r1 = 1
print(createlist(r1))
希望对您有所帮助<3
此代码无法满足您的要求。
改为尝试此代码。
import numpy as np
def createlist(r1):
for n in range(1,500):
print(np.arange(r1, r1+n, 1))
r1 = 1
#print(createlist(r1))
createlist(r1)
我想你想正确地缩进你的代码,你也想 return 每次迭代的结果,你可以试试这个
import numpy as np
def createlist(r1):
op = []
for n in range(1, 500):
op.append(list(np.arange(r1, r1 + n, 1))) # op is storing the list generated in each iteration
return op # now you can return op, a list which contains results from the loop
r1 = 1
print(createlist(r1))
p.s。请详细说明您想做什么。
每当我用变量定义 python 中的任何函数时,我都无法调用或打印函数中声明的变量的值,因此无法在后续代码行中使用该变量。 如果我能知道我在使用它时哪里错了,那将非常有帮助。
例如创建500个号码列表的代码行如下: 它给出错误:NameError: name 'r1' is not defined
def createlist(r1):
for n in range(1,500):
return np.arange(r1, r1+n, 1)
r1 = 1
print(createlist(r1))
问题是因为缩进。
您正在函数中声明 r1
。它给你错误,因为 print(createlist(r1))
看不到 r1
。所以解决方案是:
import numpy as np
def createlist(r1):
for n in range(1,500):
return np.arange(r1, r1+n, 1)
r1 = 1
print(createlist(r1))
希望对您有所帮助<3
此代码无法满足您的要求。
改为尝试此代码。
import numpy as np
def createlist(r1):
for n in range(1,500):
print(np.arange(r1, r1+n, 1))
r1 = 1
#print(createlist(r1))
createlist(r1)
我想你想正确地缩进你的代码,你也想 return 每次迭代的结果,你可以试试这个
import numpy as np
def createlist(r1):
op = []
for n in range(1, 500):
op.append(list(np.arange(r1, r1 + n, 1))) # op is storing the list generated in each iteration
return op # now you can return op, a list which contains results from the loop
r1 = 1
print(createlist(r1))
p.s。请详细说明您想做什么。