+ 3

Can you please explain the output of this code?

def fun(a): x = a**2 y = 0 while x >1: x = x -1 y += 2 return y print(fun(1) + fun(2)) Answer is 6

11th Mar 2020, 12:27 PM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
5 Answers
+ 7
Here fun(1) will be 0 because x = 1**2 = 1 is not greater than 1. And fun(2) will be 6 because x = 2**2 = 4 which is greater than 1. So loop will play untill x > 1 is true and 2 will be add in y everytime. for fun(2): x = 2**2 = 4; while 4 > 1: x = 4 - 1 y = 0 + 2 next time x will be 3 so while 3 > 1: x = 3 - 1 y = 2 + 2 again while 2 > 1: x = 2 - 1 y = 4 + 2 next time condition will false because 1 is not greater than 1 so it will not go inside the loop and finally y will be 6
11th Mar 2020, 12:34 PM
A͢J
A͢J - avatar
+ 5
fun(1)=> returns 0, since x=1**2,y=0 x>1 false, returns y fun(2) => returns 6, x=2**2=4, y=0 then x>1 true x=x-1=4-1=3, y+=2=>y=2 3>1,true x=3-1=2, y+=2=>y=4 2>1 true, x=2-1=1,y+=2=>y=6 1>1 false, returns y #now y=6 print(0+6) 6
11th Mar 2020, 12:36 PM
Jayakrishna 🇮🇳
+ 3
~ swim ~ debugging is possible here at codeplay? Because recently I can not access my computer
11th Mar 2020, 12:41 PM
APC (Inactive for a while)
APC (Inactive for a while) - avatar