+ 1
What is function of 'return' in python
in the code follows what is actually 'return' doing in the if block and what is print(number) in sixth line doing? def recursion (number): print(number) if number == 0: return recursion (number-1) print (number) recursion(3)
11 Answers
+ 3
return
is same than:
return None
It's purpose is just to terminate the function call.
print in 6th line will simply be printed after recursion is recursively called.
+ 3
In the function where the return statement is executed.
In:
def a():
print("a1")
return
print("a2")
def b():
print("b1")
a()
print("b2")
calling b would print:
b1
a1
b2
Which would mean that a's return does not terminate function b.
+ 3
amith In recursion(3), recursion(2) and recursion(1) line 6 is ran, but in recursion(0) it's not.
+ 1
recursion(3) {
print(3)
if 3 == 0:
return
recursion(2) {
print(2)
if 2 == 0:
return
recursion(1) {
print(1)
if 1 == 0:
return
recursion(0) {
print(0)
if 0 == 0:
return
" (The quoted code is skipped)
recursion(-1) {...}
print(0)
"
}
print(1)
}
print(2)
}
print(3)
}
0
I understood the concept of printing from
3
2
1
0
but here the output is
3
2
1
0
1
2
3
0
In 6 line the program print current number
0
by return which function is getting terminated?, function defined in first line or the if part? @Seb Thes
0
can you please tell me which lines are killed by return @Seb Thes
0
You can build up the output of recursion(3) by thinking of each layer in the recursion like so:
3
recursion(2)
3
3
2
recursion(1)
2
3
3
2
1
recursion(0)
1
2
3
3
2
1
0
1
2
3
Note that the if block (base case of the recursion) only runs when the argument of the recursion function is 0. The return then stops any further recursions or printing and the function calls ends right there.
0
@Njeri
after if number==0:
return
get satisfied line 5 and 6 is not going to execute right?
0
amith Yes.