+ 2
[Solved] Hi, I have a question about a very basic program that I can't understand in python
Why does this program output 1 instead of 2? a=1 def f(x): x=2 f(a) print(a)
7 ответов
+ 5
Hi Azi ,
In your second question,
Because a is global variable, it becomes your x, and all you do in your function defination affect a as you call it.
But in first question, a can not be a = 1 and a = 2 at the same time. So which is global? a = 1 is global. so it is your output
+ 3
Because x = 2 inside the function and u are printing the value of x outside the function
https://code.sololearn.com/cRTVvwNkzy0t/?ref=app
+ 2
You are printing 'a' a global variable. And you are modifying x in function and it's a local variable to that function. Not exist outside of that function. 2 are different variables, just a value is copiyed into x variable.
+ 2
Thanks for answering, however I don't understand why when I use a list instead of a string or number it works even without "return" :
a=[1,2,3]
def f(x):
x.append(4)
x[0]=0
f(a)
print(a)
(it's gonna output [0,2,3,4] )
+ 2
Just take a look at " pass by value and pass by refference " . And it's difference.
List is collection of data so it is passed by a refference.. so change in original list will reflect back outside function also.
But single values (string and number.. immutable objects.) are passed by value.
Edit:
Azl
https://mathspp.com/blog/pydonts/pass-by-value-reference-and-assignment
hope it helps...
+ 2
Thank you! Now I understand :)
I didn't know about python's "pass by assignment" method and I thought that it was "pass by reference".
+ 1
It's because the variable a was made to be the same as the variable x . So because a==x==2 the code will print 2 not 1