-2

I am trying this code.

Function incre_test is recursive unless it satisfy the condition.

I expect 5 as result but it returns None.

What is the best practice for this pattern?

def incre_test(i):
    if i > 4:
        return i
    i = i + 1
    incre_test(i)

res = incre_test(0)
print(res) // why None???
whitebear
  • 11,200
  • 24
  • 114
  • 237
  • 3
    Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – CrazyChucky Jan 29 '22 at 02:17

3 Answers3

0

Try this:

def incre_test(i):
    while not i == 5:
        i+=1
    return i

res = incre_test(0)
print(res)

You have to use a while <bool>: loop to run a script (in this case i+=1) until the condition given is true.

0

Using a loop inside the function might do you better

such as

def incre_test(i):
    while i < 5:
        i += 1
    return i
Azearia
  • 19
  • 3
0

It's because your function is not returning anyting unless the parameter is greater than 4, so all you have to do is to add a return statement over the recursive call of the function, like this...

def incre_test(i):
    if i > 4:
        return i
    return incre_test(i+1)

res = incre_test(0)
print(res)

Output:-

5
MK14
  • 481
  • 3
  • 9