在函数内访问函数的变量

Accessing the variable of a function within a function

假设我有来自用户输入的积分的下限值和上限值。我首先询问下限,然后检查其有效性。然后为了比较我的上限值和我的下限值我做了一个嵌套函数,这样我也可以要求用户输入上限值,检查它的有效性并确保我的上限大于我的下限(因为你知道集成),如下面的代码所示。

def LowLimCheck():
    while True:
        try:
            a = float(input("Please enter the lower limit of the integral: "))
            break
        except ValueError:
            print("Invalid input. Please enter a number.")
    print("You have chosen the lower limit: ", a)      

    def UppLimCheck():
        b = -1
        while b <= a:
            while True:
                try:
                    b = float(input("Please enter the upper limit of the integral: "))
                    break
                except ValueError:
                    print("Invalid input. Please enter a number.")

            if b <= a:
                print("The upper limit must be bigger than the lower limit!")
        print("You have chosen the upper limit: ", b) 
        return b           
    UppLimCheck()  
    return a

现在这一切都很好,直到我实际需要使用值 a 和 b,因为我需要将这些值放入我设置的积分中。它基本上是辛普森法则的一般积分,现在很容易理解。所以我将函数定义为:

def simpsonsRule(func, a, b, N):

    <insert code here>
    <insert code here>

    return d

好的,所以我的函数基本上允许用户插入任意函数,上限 (a)、下限 (b) 和 N(辛普森规则中的条带数),然后输出 d,这是对根据辛普森法则对上述任意函数进行积分。我现在的问题是,当我尝试打印答案时,我可以将变量 a 取出并放入积分中,但我不能将变量 b 取出,因为它在函数中!例如,如果我现在打印积分值(比如在 sin(x) 和 N = 20 的情况下)

print(simpsonsRule(lambda x:np.sin(x), a, b, 20)

所以我知道 a 和 b 值在它们自己的函数中是局部的。现在对于 a 的值,我可以很容易地这样做以获得值 a

k = 0 #initialising the variable
k = LowLimCheck()
print(simpsonsRule(lambda x:np.sin(x), k, b, 20)

因为 k 调用了 LowLimCheck(),returns 我可以将 a 的值放入我的函数中。但是我怎样才能得到嵌套在第一个函数中的 b 值呢?我想基本上使用 b 。有办法解决这个问题吗?

对于冗长的问题深表歉意,并提前致谢!

您可以 return 来自 LowLimCheck() 的元组:

def LowLimCheck():
    ...
    b = UppLimCheck() 
    return (a,b)

然后在调用 LowLimCheck() 时解压它们

a, b = LowLimCheck()

更新:

在对您问题的最直接回答中,LowLimCheck() 变为:

def LowLimCheck():
    while True:
       try:
            a = float(input("Please enter the lower limit of the integral: "))
            break
        except ValueError:
            print("Invalid input. Please enter a number.")
    print("You have chosen the lower limit: ", a)      

    def UppLimCheck():
        b = -1
        while b <= a:
            while True:
                try:
                    b = float(input("Please enter the upper limit of the integral: "))
                    break
                except ValueError:
                    print("Invalid input. Please enter a number.")

            if b <= a:
                print("The upper limit must be bigger than the lower limit!")
        print("You have chosen the upper limit: ", b) 
        return b     

    b = UppLimCheck()   # Storing the b
    return (a,b)        # Passing b out with a in a tuple

然后打电话

a, b = LowLimCheck()

最后,

print(simpsonsRule(lambda x:np.sin(x), a, b, 20)

替代解决方案(更实质性的变化,但更好的代码结构——如原始评论中所述;更扁平、更易读、范围考虑更少):

def LowLimCheck():
    while True:
        try:
            a = float(input("Please enter the lower limit of the integral: "))
            break
        except ValueError:
            print("Invalid input. Please enter a number.")
    print("You have chosen the lower limit: ", a)      

    return a

def UppLimCheck(a):
    b = -1
    while b <= a:
        while True:
            try:
                b = float(input("Please enter the upper limit of the integral: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")

        if b <= a:
            print("The upper limit must be bigger than the lower limit!")
    print("You have chosen the upper limit: ", b) 

    return b  

然后:

lowLim = LowLimCheck()
upLim  = UppLimCheck(lowLim) # pass in lowLim as an argument

print(simpsonsRule(lambda x:np.sin(x), lowLim, upLim, 20)