+ 5
Nested function in Python
Hi there, I don't understand why the following code's output is: None 2. Could you please help me? I assumed the output should be: 1 1 because if x = 2 is not equal to 1, then we need to substact 1 from x, it becomes 1 and function(1) is executed which means the returned value is 1. In the meantime we changed the value of x from 2 to 1, and that is why I thougt the print function will output 1 and 1. def function (x): if x == 1: return x else: x-=1 function(x) x = 2 print (function(x),x)
3 odpowiedzi
+ 10
The function should always return something, if nothing returns, then 'None' will return
+ 1
Function arguments can be used as variables within the function definition. But they cannot be referenced from outside the function definition. This also applies to other variables created in the function body.
Debug:
def function(x):
if x == 1:
return x
else:
x-=1
return function(x)
x = 2
print(function(x),x) # 1 2
P.S: <<The function call must be made from the outside, for this "return" is applied.>>