Home > Software engineering >  Basic Python if statements
Basic Python if statements

Time:08-20

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?

Don't know where I misunderstand.

Thanks

CodePudding user response:

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.

CodePudding user response:

when call g(-x), in your case, it equals g(-(-1)), which is g(1)

CodePudding user response:

When you specify def f(x) or def g(x), you're saying that, in the following context, x is going to be the name for the actual parameter of these two methods, regardless of the x=0 defined outside.

That being said, the following lines are equivalent:

f(-1)
g(1)  # because if x < 0 is True
2 * 1   3
5

From your code, it is not exactly clear to me which of the xes you'd like to refer to the global x=0 and which of them should refer to the function's parameter, like -1 in your example. You should make this distinction yourself and name them differently, for example, x and y. As far as I know, if you name your function parameters the same as your global variables, you lose access to the global variables from within the function body (except for globals tricks).

  • Related