Why is the output "apple"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the output "apple"?

Why is the output not "banana"? https://code.sololearn.com/c2rQ1jWYh0oy/?ref=app

21st Nov 2019, 2:59 PM
Satyam
2 Answers
+ 4
y in the function is a local variable, it will automatically be destroyed when function call terminates. You can stop this by declaring the variables to global: def x(): global y y = "banana"
21st Nov 2019, 4:31 PM
Seb TheS
Seb TheS - avatar
+ 7
Please keep in mind, that *y* defind in first line is a different object as *y* defined in function: y="apple" print(id(y)) def x(): y="banana" print(id(y)) print(y) x() print(y) #output: 139793837036272 apple 139793837036400 apple
21st Nov 2019, 4:39 PM
Lothar
Lothar - avatar