Python Forum

Full Version: Nested function problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone, I created this nested function to solve this formula: sqrt(sin(x)*(cos(x)) but it doesn't work. Where am I wrong?
Thanks
chipx

this is the code:

Output:
[output]import math def f1(x): a = math.sqrt(b) def f2(x): b = math.sin(x)*c def f3(x): c = math.cos(x) return c return b return a f1(5)
[/output]
An embedded function still needs to be called. f1() never calls f2() and f2() never calls f3().
I think there is an indentation error. f3() never returns a value. f2() returns c, which is a variable inside f3(). f1() has two returns and will never get to "return a". The code should look more like this:
def f1(x):
    def f2(x):
        def f3(x):
            return math.cos(x)
        return f3(x) * math.sin(x)
    return math.sqrt(f2(x))
Code like this it should always be accompanied by a disclaimer.

"This code is written for the purposes of learning about embedded functions. Any use of this code would be a big mistake."
(Oct-21-2020, 03:01 PM)deanhystad Wrote: [ -> ]An embedded function still needs to be called. f1() never calls f2() and f2() never calls f3().
I think there is an indentation error. f3() never returns a value. f2() returns c, which is a variable inside f3(). f1() has two returns and will never get to "return a". The code should look more like this:
def f1(x):
    def f2(x):
        def f3(x):
            return math.cos(x)
        return f3(x) * math.sin(x)
    return math.sqrt(f2(x))
Code like this it should always be accompanied by a disclaimer.

"This code is written for the purposes of learning about embedded functions. Any use of this code would be a big mistake."


Thank you! but now what function do I call? to get a result.
In the example, f1 calls f2 (in the return statement), and f2 calls f3. To get your answer, call f1(value)
I imported math tried to call f1 but it gives me error:

Output:
f1(5)
"ValueError: math domain error"
You will get that trying to take the square root of a negative number. sin(5) is negative, cos(5) is positive. f2(5) returns a negative number and f3(5) crashes when it tries to calculate the square root.

You should probably add some code to catch that problem and provide a more meaningful error message.
I tried changing "cos" to "log10" and now it works.
Thank you!

Output:
import math def f1(x): def f2(x): def f3(x): return math.log10(x) return f3(x) * math.sin(x) return math.sqrt(f2(x)) f1(3)0.25948286130604603
Until someone calls f1(4).
Assuming this is actually a proof of concept, that is fine, but as @deanhystad points out, you really should have some checks to make sure you are not trying to get the square root of a negative number.