Home > OS >  Python loop and return pattern
Python loop and return pattern

Time:01-29

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???

CodePudding user response:

Using a loop inside the function might do you better

such as

def incre_test(i):
    while i < 5:
        i  = 1
    return i

CodePudding user response:

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.

CodePudding user response:

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
  •  Tags:  
  • Related