Is it possible to define a Python function that modifies a v

Is it possible to define a Python function that modifies a variable defined outside of the function? For example, in the following piece of code below is it possible that the program prints two different values? If not, explain why not, or if so fill in the function f() that would achieve this result. def f(): x = 0 print(x) f() print(x)

Solution

To understand the function let us take an example in python somehow similar to your piece of code-

def f(p, a):

    p = 2

    a.append(4)

    print \'In f():\', p, a

def main():

    p = 1

    a = [0,1,2,3]

    print \'Before:\', p, a

    f(p, a)

    print \'After: \', p, a

main()

Output:

Before: 1 [0, 1, 2, 3]

In f(): 2 [0, 1, 2, 3, 4]

After: 1 [0, 1, 2, 3, 4]


p is an int which is basically immutable, and their is a copy is passed to the defined function, so in the function are changing only the copy of data not the original data.

a is a list which is mutable, and a copy of the pointer is passed to the defined function so a.append(4) changes the contents of the list. However, you you said a = [0,1,2,3,4] in your function, you would not change the contents of a in main() function of the program.

In other words Python is basically a pure pass-by-value language. A python variable stores the location of an object in memory space. The Python variable only stores the copy and does not store the original object.When you pass a variable to a function, you are passing a copy of the address of the object which is pointed by the variable.

Hope now you understand the concept. THANKYOU

 Is it possible to define a Python function that modifies a variable defined outside of the function? For example, in the following piece of code below is it po

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site