在函数

时间:2017-12-27 21:44:05

标签: python python-3.x integration nested-function simpsons-rule

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

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(Simpson规则中的条带数)并且它吐出d这是积分的评估Simpson规则的任意函数。我现在的问题是,当我尝试打印答案时,我可以将变量a取出并放入积分但我不能将变量b取出,因为它在函数中!例如,如果我现在打印积分值(例如在sin(x)和N = 20的情况下)

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

所以我知道a和b值在它们自己的函数中是局部的。现在,对于a的值,我可以轻松地执行此操作以获得值

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

因为k调用LowLimCheck(),它返回我可以放入函数的值。但是如何获得嵌套在第一个函数中的b值?我基本上想用b。有没有办法解决这个问题?

为这个冗长的问题道歉并提前致谢!

1 个答案:

答案 0 :(得分:1)

你可以从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)