0
a=0

def test():
    global a
    a=a+1
    if a==10:
        return 12333
    else:
        print(a)
        test()

print(test())

Above is my code。 enter image description here

khelwood
  • 55,782
  • 14
  • 81
  • 108
神木马
  • 1
  • 1
  • 1

2 Answers2

1

The reason why this is not currently working is because there is not currently anything being returned to your original print statement.

Your print(test()) call will increment a by one, print(a) and then call itself again, which is were you get your recursion, however nothing is ever returned to the original function call.

This can simply be fixed by adding return to the function call within the function so that you have:

a=0

def test():
    global a
    a=a+1
    if a==10:
        return 12333
    else:
        print(a)
        return test()

print(test())

This is where the simple language of Python falls short in comparison to Java as it doesn't inform you that something is wrong, whereas Java and other languages would tell you that you are missing a return statement.

Even more in depth information can be found here

karel
  • 5,489
  • 46
  • 45
  • 50
0

You should make the function test to also return the returning value of the recursive call; otherwise it would return None implicitly without an explicit return statement.

Change:

test()

to:

return test()
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • if the answer helped you @神木马 , you can [accept the answer](https://stackoverflow.com/help/someone-answers) and also consider upvoting. It helps the answerer and helps you too! – Paritosh Singh Feb 26 '19 at 09:50