0

Strange double-brackets arguments in Python

Hello, I've recently had a challenge with this Python code: def x (a=0): def y (b=a): return a+b if a == 0: return y return y(a) print(x(2) + x()(3)) The last line has this weird thing: x()(3). This makes something strange happen: 1. The x function treats the empty bracket as absence of the "a" argument and uses the predefined value 0 for it: x() = x(a) 2. The x function takes 0 to 1 arguments. If you put 0 and 3 in one parentheses as in (0, 3), you will get an error, since that's 2 arguments: x(0, 3) = x(a, b) –> error 3. The y function treats 3 from the second parentheses as the "b" argument, i.e. the second argument that the x function for some reason didn't treat as such: x()(3) = x(a)(b) Hence the question: why do these two functions treat these arguments differently? And what are these double brackets anyway? How do we use them? If you could send me a link to some page where this thing is explained, I'll be grateful too. I just don't even know how to google it 😅

28th Mar 2022, 1:19 PM
chalupa bazooka
chalupa bazooka - avatar
3 Answers
+ 5
If a is 0, y() will be returned. y() adds b to a. If b is not provided, it will be a; if it is provided (2nd parentheses), it's whatever we input. I simplified the function for demonstration and added a comment. I recommend to print out values when you are not sure what they would be. https://code.sololearn.com/c7BMp0hIBIoG/?ref=app
28th Mar 2022, 1:57 PM
Lisa
Lisa - avatar
28th Mar 2022, 2:04 PM
Simon Sauter
Simon Sauter - avatar
0
Lisa, Simon Sauter, thank you, guys! Now I know that it's nested functions.
29th Mar 2022, 11:25 AM
chalupa bazooka
chalupa bazooka - avatar