0
CAN anyone explain what return does here . Pls read full description , thanks...
def factorial (n) : x = 1 while n >= 1 : x = x*n n = n - 1 return x What I understand is : x = 1 while n >= 1 , x changes to x*n , i.e n(as x = 1) and then n becomes n-1 and we again multiply it with x which is now n only because we returned x but what code will execute after return x it should be x= 1, shouldn't it
6 ответов
+ 2
after return nothing execute.
if n == 1 , then the loop run once and rrturn 1.
IF n == 2 then the loop run twice and x = 2 * 1 .
if n == 3 x = 3 * 2 * 1
.
.
.
if n == m , x = m * m - 1 * ... * 2 * 1
+ 2
The function won't return until it snaps out of the while loop. i.e. it won't return until n < 1. The value returned at the end will be the factorial of n. The while loops calculates the following:
for n=4
->x= 1*4 -> (n becomes 3)
->x=4*3 -> (n becomes 2)
->x=12*2 -> (n becomes 1)
->x=24*1 -> (n becomes 0)
It stops here since the condition while n>=1 is not satisfied
->returns x = 24..
Hope that helps.
+ 2
It really helped Kishore, Szabbo and Venkatesh .
+ 1
Loop exist between while n >=1 to n = n-1, right? So it will stop when n== 1 , only then( after n times reading the Loop ) the python goes to read return?? Am I right now???
+ 1
Let us unroll the while loop with n = 3. It becomes x = 1 * 3 * 2 * 1. At this point, x is evaluated and the while loop is completed. The next statement is return x. So 6 is returned to the caller.
+ 1
Thanks everyone for helping me out , 😄😄😇