Home > Software engineering >  how can i change the value of variable just for a specific function?
how can i change the value of variable just for a specific function?

Time:05-14

x=2
def fun():
    y=x 2
    print(y)
def main_fun():
    x=10
    fun()

print(x)
fun()
main_fun()
fun()
print(x)

I want the that the value of x when i call main_fn be 10. But when i call fun() it will remain 2. I have tried using global but it is not giving the required result.

I want this output:

2
4
12
4
2

CodePudding user response:

Pass that value as an argument in that function Suppose there is a variable x

x=2
def fun(a=x)
   ...

def main_fun(a=y)
   ...

fun()
main_fun()

Instead you can also play with while calling

x=2
def fun(a=x)
   ...

def main_fun(a=x)
   ...

fun()
main_fun(5)

CodePudding user response:

x=2
def fun(x):
    y=x 2
    print(y)
def main_fun():
    y=10
    fun(y)

print(x)
fun(x)
main_fun()
fun(x)
print(x)
  • Related