本文介绍了如何在函数调用在python中完成时访问函数的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上发现,当函数调用完成后,函数的局部变量不能从外部访问。我尝试执行该程序,但是它引发了一个错误,那个变量没有被定义。我的代码是

  xyz = list()
n = 0
def长度(g):
i = 0
n = g
v = input(no of)
while i< v:
c = input(输入第一维:)
j =输入(输入第二维:)
i = i + 1
xyz.append(c)
xyz.append(j)
返回c
返回j
返回n
def prod():
全局c
在xyz中为i:
如果n print上传另一个
elif n == c和n == j:
printAccepted
else:
print裁剪
length(input(输入长度))
prod()
print xyz

它会抛出像这样的错误


解决方案

我想这是你想做的事情

  xyz = list()
n = 0
def长度(g):
i = 0
n = g
v = input(no of)
global xyz
while i< v:
c = input(输入第一维:)
j = input(输入第二维:)
i = i + 1
xyz.append(c)
xyz.append(j)
return c,j,

$ b def prod():
global xyz
c,j,n = length(input(ENter the length))
for i in xyz:
if n printUpload another
elif n == c and n == j:
printAccepted

$ print b



$ b $
$ b

输出

 长度2 
no 2
输入第一维度: 1
输入第二维:2
裁剪
裁剪
[1,2]


I found on the net that local variables of functions can't be accessed from outside when the function call has finished.I try to execute the program but it throws an error that variable is not defined. My code is

xyz=list()
n=0
def length(g):
    i=0
    n=g
    v=input("no of")
    while i<v:
        c=input("Enter the 1st dimension:")
        j=input("Enter the 2nd dimension:")
        i=i+1
        xyz.append(c)
        xyz.append(j)
        return c
        return j
        return n
def prod():
    global c
    for i in xyz:
        if n<c and n<j:
            print "Upload another"
        elif n==c and n==j:
            print "Accepted"
        else:
            print "Crop it"
       length(input("ENter the length"))
       prod()
       print xyz

It throws error like this

解决方案

I guess this is what you would want to do

xyz=list()
n=0
def length(g):
    i=0
    n=g
    v=input("no of")
    global xyz
    while i<v:
        c=input("Enter the 1st dimension:")
        j=input("Enter the 2nd dimension:")
        i=i+1
        xyz.append(c)
        xyz.append(j)
        return c,j,n


def prod():
    global xyz
    c,j,n = length(input("ENter the length"))
    for i in xyz:
        if n<c and n<j:
            print "Upload another"
        elif n==c and n==j:
            print "Accepted"
        else:
            print "Crop it"

prod()
print xyz

Output

ENter the length 2
no of 2
Enter the 1st dimension: 1
Enter the 2nd dimension: 2
Crop it
Crop it
[1, 2]

这篇关于如何在函数调用在python中完成时访问函数的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:03