+ 1

Can any one help me understand the below code???

def spam(a): def eggs(): a=[5] return a def bacon(): a[0]+=1 eggs() bacon() return a[0] print(spam([2])) Output:3(how?!)

14th Jul 2017, 5:03 PM
AdityaNikhil
AdityaNikhil - avatar
4 Answers
+ 3
spam([2]) [2] is a List with only one element the number 2 The list is passed into the method spam spam has 2 sub methods eggs and bacon that are defined The eggs method is called inside the eggs method a new variable a is created and has the list [5] set to it. This variable a shadows the a variable that was passed into the method and is not the same. a is returned from the eggs method, but is not used, so the entire eggs method has no effect. The bacon method is called. inside the bacon method the line: a[0]+=1 retrieves the value of the 0 position element of the list a (2) and increments its value by 1 The list a now equals [3] Now the return a[0] line runs retrieving the value 3 at the 0 position of the list a and returns it to the print method outputting 3.
14th Jul 2017, 5:42 PM
ChaoticDawg
ChaoticDawg - avatar
+ 8
Actually, it's a matter of proper understanding of variable scopes. What spam does, is it ultimately only increases its argument by 1 with its inner method bacon() (a[0]+=1) Earlier, the eggs() method returns a equal to [5], but it is done within the local spam() method scope. When it goes down, it executes the bacon() method, which again recalls a[0] as spam() method's parameter (which you provide as [2]). So it augments it by one and then returns it. So it gives you output 3
14th Jul 2017, 5:27 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 7
This has to do with variable scopes, this thread explains it pretty well https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules (: As for the code above: 1) list [2] gets passed to method spam 2) sub method of spam (eggs) gets called. a=[5] doesnt assign the value [5] to the list [2] passed to spam, but rather its a declaration of variable a within the scope of the eggs method and it has nothing to do with the initial list passed to spam.The local scope a then gets returned to nothing because eggs is called but not assigned to anything 3) sub method of spam (bacon) gets called. in this case a[0]+=1 adds 1 to the value of the first item in list named a, but since there are no lists named a in the local variable scope of bacon, it looks for the next scope level and finds the variable a in its parent method spam, so it assigns the value to it.
14th Jul 2017, 5:35 PM
Maya
Maya - avatar
+ 2
Congrats for gold, Maya! 👏👏👏👏👏 https://www.sololearn.com/Discuss/454972
15th Jul 2017, 3:12 AM
David Ashton
David Ashton - avatar