Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Basic Python if statements

I’m learning Python and I’m trying to understand this line if I call f(-1):

x = 0
def f(x):
   if x < 0:
      return g(-x)
   else:
      return g(x)
def g(x):
      return 2*x + 3

If I call f(-1) I get 5. But I incorrectly interpret that I would get 1. This is my interpretation process:

Since x=-1 it should return g(-x). There is no def g(-x) though. However if it returns def g(x) then we should get 2*x+3, which is 1?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Don’t know where I misunderstand.

Thanks

>Solution :

Think of g as the function and x as input to the function.
Furthermore, x is also just like any other variable name.
This means I could instead rename the x variable in the g function to anything I want.
I could also call g anything I want.
Example:

def f(x):
   if x < 0:
      return grumpy_function(-x)
   else:
      return grumpy_function(x)

def grumpy_function(cool_value):
      return 2*cool_value + 3

Now try to walk through the logic using these above functions…
f(-1) causes the if statement x<0 to be true.
So we will execute the line return grumpy_function(-x)
We know that x=-1, so this means -x = -(-1) = 1.
Therefore cool_value is actually 1 not -1.
Now go to grumpy_function: 2*1+3 = 5.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading