How this code works | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How this code works

please help me with this code https://code.sololearn.com/cU07sz0ELOx2/?ref=app

30th Aug 2018, 4:40 PM
moamen
moamen - avatar
4 Answers
+ 9
Okay, I'll try to explain as best as I can. Notice on line 1 that we have `x=0` as parameter for function `f`. That means `x` is an optional parameter. It defaults to 0 whenever we call `f` without passing any arguments. Line 2 isn't doing anything in this program. You can remove it and you'll still get the same output. On lines 3 and 4, the function `g` is defined as an inner function inside function `f`. It takes a parameter `y` and prints it. Then on line 5 we print `x`. The tricky part is understanding what line 6 is doing. Function `f` is returning `g`. That can seem like a strange concept, but yes, functions can return other functions. (this is pretty common when programming in a functional paradigm) On line 7 you are calling `f` without passing any arguments, as evidenced by the empty parenthesis. Thus we know that `x` is set to 0, which is its default value. Since `f` returns `g`, what line 7 is doing is passing (1) as argument to function `g` after it is returned from `f`. I hope this helps clearing your doubts. If you still have questions, feel free to ask!
30th Aug 2018, 5:01 PM
Eduardo Petry
Eduardo Petry - avatar
+ 8
Which part of it you don't understand?
30th Aug 2018, 4:46 PM
Eduardo Petry
Eduardo Petry - avatar
+ 1
the output of f()(1) is 1 for y or y should equals x
30th Aug 2018, 4:47 PM
moamen
moamen - avatar
+ 1
Thanks a lot Eduarda i understood it because of you
30th Aug 2018, 5:09 PM
moamen
moamen - avatar