[Solved] Hi, I have a question about a very basic program that I can't understand in python | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 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)

30th Dec 2021, 11:16 AM
Azl
7 Respuestas
+ 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
30th Dec 2021, 12:52 PM
SoloilSole
SoloilSole - avatar
+ 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
30th Dec 2021, 11:28 AM
Shino
Shino - avatar
+ 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.
30th Dec 2021, 11:31 AM
Jayakrishna 🇮🇳
+ 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] )
30th Dec 2021, 12:08 PM
Azl
+ 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...
30th Dec 2021, 12:13 PM
Jayakrishna 🇮🇳
+ 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".
30th Dec 2021, 12:48 PM
Azl
+ 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
1st Jan 2022, 7:21 AM
Emmanuel Biamah