1
def fun(x):
    x += 1
    return x

x = 2
x = fun(x + 1)
print(x)

It is said that the variable , declared outside the function , cannot be written but read in a function, unless the variable is declared global , so how can here the value of x is updated?

Rohan
  • 55
  • 6
  • 3
    The `x` inside the function is totally unrelated to the `x` outside the function. It refers only to the argument named in the function definition: `def fun(x):`. Change all of the `x` inside the function to `y` and the program will behave exactly the same – roganjosh May 25 '20 at 09:06
  • Please show us the error message – Aynos May 25 '20 at 09:08
  • @JonasX there is no error message. The question is about scope. It should be easily duped, to give the OP a more-thorough explanation, but I'm struggling to find the most appropriate target – roganjosh May 25 '20 at 09:09
  • @JonasX Please read the question carefully before writing a comment. – Klaus D. May 25 '20 at 09:10
  • i overread that sry – Aynos May 25 '20 at 09:11

1 Answers1

0
def fun(x):
    x += 1                  => Adds 1 to the x from the method argument
    return x                => Returns the new value of x

x = 2                      
x = fun(x + 1)              => Call the function as fun(2 +1) which returns 3 + 1 and assigns to the variable x
print(x)                    => Prints the latest x value which is 4.

To further clarify, let the change the program a little bit without affecting the result of the program:

def fun(y):
    y += 1
    return y

x = 2
x = fun(x + 1)
print(x)

Here, the variables used inside the function are totally different than the one that is used to call the function.

So, The value of x is updated only because the functions returns the updated value of x, which is then assigned to x as x = func(x), It has nothing to do with the variable names.

Pratik Joshi
  • 389
  • 4
  • 13
  • You have explained every line. Yet you are not directly answering the question. – Klaus D. May 25 '20 at 09:12
  • Okay. So let me try to summarize: The value of x is updated because the functions returns the updated value of x, which is then assigned to x as x = func(x) – Pratik Joshi May 25 '20 at 09:14
  • The result of the program will be the same, even if you use another variable name inside the function definition. – Pratik Joshi May 25 '20 at 09:15
  • 1
    You might want to edit your question and add that there. – Klaus D. May 25 '20 at 09:16
  • The one thing I think needs adding is "function scope" or similar, which is at least something they can search to find further info – roganjosh May 25 '20 at 09:22