Nested function problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Nested function problem (/thread-30451.html) |
Nested function problem - chipx - Oct-21-2020 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]
RE: Nested function problem - deanhystad - Oct-21-2020 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." RE: Nested function problem - chipx - Oct-21-2020 (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(). Thank you! but now what function do I call? to get a result. RE: Nested function problem - jefsummers - Oct-21-2020 In the example, f1 calls f2 (in the return statement), and f2 calls f3. To get your answer, call f1(value) RE: Nested function problem - chipx - Oct-21-2020 I imported math tried to call f1 but it gives me error: "ValueError: math domain error"
RE: Nested function problem - deanhystad - Oct-21-2020 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. RE: Nested function problem - chipx - Oct-21-2020 I tried changing "cos" to "log10" and now it works. Thank you!
RE: Nested function problem - deanhystad - Oct-21-2020 Until someone calls f1(4). RE: Nested function problem - jefsummers - Oct-21-2020 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. |