+ 5
How do you pass variables from one function to another without making it global, i havent been able to find out how.
ex def var_1(): x = 1 a = 2 def var_2(): y = x b = a print (y, b) var_2() I understand why this doesn't work but I'm trying to find out how to make it work without making x and a global variables.
9 Answers
+ 7
You could also use the return statement as follows.
def var_1():
x = 1
a = 2
return x, a
def var_2():
y, b = var_1()
print(y, b)
var_2()
+ 5
[Warning: this answer gets weird]
Ok...to get a variable created you have to run var_1() somehow; to get values named in-scope (local, since you don't want global)
Returning the vars *does* keep the "id" the same if that's what you're after...you're just installing new 'names' for a value that has not lost all of its references yet (the variable isn't passed; the name switches, even if it's the same in both places)...here's a nice article about names vs. values:
https://nedbetchelder.com/text/names.html
#####
Now...here's a way that's...neat but kindof wrong...if you accept that running a function creates a "local variable scope frame":
https://code.sololearn.com/c2uDPhi23Ngo/?ref=app
That's kindof the function's vars when it ran, but It's also kindof weird.
(I'm only really including this to emphasize "local scope")
+ 3
using this code
def var_2(x,a):
y = x
b = a
print(y,b)
def var_1():
x = 1
a = 2
var_2(x,a)
var_1()
+ 3
Only on inner functions otherwise no way.
+ 2
KRISHNA I how do i call var_2 () ?
+ 2
Diego's answer is definitely the right one. How ever, you can also look at the concept of nonlocal variable if you are working in python 3. It localises the value of a variable within two functions (suppose A and B) where consider B to be an inner function declared in the statement of A function. If A is declared in the statement of another function, say X, then that nonlocal variable will not influence anything in function X.
Example:
def X():
var = 3
def A():
var = 2
def B():
nonlocal var
var = 1
print(var)
B()
print (var)
A()
print(var)
X()
Answer:
1
1
3
+ 1
Kirk Schafer Indeed... that approach is "cringy" đ€Ł
Might I propose two less cringy options to consider...
https://code.sololearn.com/cz9q6M621LSy/?ref=app
and
https://code.sololearn.com/cNMHNsZzqIjw/?ref=app
Personally, I like the namedtuple because I prefer using the dot notation over brackets with quotes.
0
Use can use inner functions or looping functions
def var_1() :
X=1
A=2
def var_2() :
Y=X
B=A
print(Y, B)
0
All of them are good actualy everybody has theyr way of coding there are millions of ways to do it just do it how you like it