'how can i change the value of variable just for a specific function?
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
Solution 1:[1]
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)
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Harsh Vishwakarma |
Solution 2 | Rida Rizwan |