-2

Nothing is returned when I try iterating a function in Python. Code is like this

def count(num):
    if (num > 10):
        return(num)
    if(num<=10):
        new = num + 1
        count(new)     
nummer = count(8)

If I do count(22), it returns 22. But when I do count(8), it doesnt return anything. I would like this function to return '11' but it return nothing. Probably something wrong in my thinking but I really can't figure it out. I hope someone can help me.

Thx, Peter

  • 1
    Where do you return if number is less than 10? – Sayse Jul 15 '22 at 07:22
  • then it starts the function again. It adds +1 and then goes to the function again until it reaches 11. So, it only should return 11 or if you have entered a higher number, it should return this one. – Aurora Borealis Jul 15 '22 at 07:25
  • 1
    No, it doesnt. It *calls* the function again, but the original function call still needs something to return (likewise for any subsequent function calls) – Sayse Jul 15 '22 at 07:25

3 Answers3

2

Your second recursive call lacks a return statement, so that branch will always return None. You will need to explicitly return the result of count there, i.e.

return count(new)
mitch_
  • 1,048
  • 5
  • 14
1

you cannot return the value in other conditions. Try this

def count(num):
    if (num > 10):
        return(num)
    if(num<=10):
        new = num + 1
        return count(new)     
nummer = count(8)
Mehmaam
  • 573
  • 7
  • 22
1

You actually need to include a second return, in case your number is lower or equal than 10. Besides, you could have a slightly shorter code. Calling the function is not sufficient.

You are trying to evaluated whether a number x is greater or lower than 10. But this number can EITHER be greater OR lower. Therefore when you put

if num>10:
  pass

you don't need another if statement, since if num is not greater than 10 it is lower or equal to 10.

def count(num):
    if (num > 10):
        return(num)
    else:
        new = num + 1
        return count(new)     
nummer = count(8)
Maxime Bouhadana
  • 438
  • 2
  • 10