0

Recursive call is None?

Why is recursive call of this function None for x = 2? def function(x): if x == 1: return x else: x -= 1 print(function(x)) function(x) x = 2 print(function(x), x) Output: 1 None 2

25th Oct 2023, 6:33 PM
Jovica Spasic
Jovica Spasic - avatar
2 Réponses
+ 4
Oh, I just realized that return keyword is missing in front of recursive function call: return function(x)
25th Oct 2023, 6:56 PM
Jovica Spasic
Jovica Spasic - avatar
+ 3
Jovica Spasic you might want to change == to <= to prevent infinite recursion for x<1. def function(x): if x <= 1: return 1 else: x -= 1 print(function(x)) return function(x) #test for x in range(-5,5): print(function(x), x)
25th Oct 2023, 9:53 PM
Bob_Li
Bob_Li - avatar