-1

I'm currently playing with recursive functions and I have a question.

I don't understand why this one work

a, b = map(int, input().split())
def gcd(a,b):
    if a%b == 0:
        return b
    else:
        return gcd(b,a%b)   
print(gcd(a,b))

but this one doesn't

a, b = map(int, input().split())
def gcd(a,b):
    if a%b == 0:
        return b
    gcd(b,a%b)

print(gcd(a,b))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    You need to actually `return` something for a function to work... that's literally the only difference. Why do you expect the second to work? – Dúthomhas Sep 17 '22 at 03:37
  • Because the code here actually work without two returns. 'def recursive_function(i): if i == 100: return print(i) recursive_function(i+1) print(i) recursive_function(1)' – Myojoong Kim Sep 17 '22 at 03:42
  • 2
    Apples to oranges. That's not returning a value, just printing stuff. Consider this: if you change something and it breaks, that something must be important. What's different between a procedure that just prints stuff and a function that returns a value? – Dúthomhas Sep 17 '22 at 03:47
  • I understand your point. having return in the code changed everything. I understand that. But try this one. 'a, b = map(int, input().split()) def gcd(a,b): if a%b == 0: return b gcd(b,a%b) print('a') print(gcd(a,b))' When I entered 192 162 as inputs, I expected it would show me a result like this '192 162 a a a 6'. However, the result was '192 162 a a a None'. I don't understand why the last value should be None for this case. – Myojoong Kim Sep 17 '22 at 03:53
  • I know my question is a stupid question. But I just wanted to fully understand how this function works. – Myojoong Kim Sep 17 '22 at 03:53

1 Answers1

1

Though the answer appears in the comments, I thought this is an opportunity to demonstrate how python tools can help you find similar errors like this in the future.

$ pylint --disable=invalid-name,redefined-outer-name,missing-function-docstring,missing-module-docstring main.py
************* Module Downloads.main
main.py:2:0: R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)

-------------------------------------------------------------------
Your code has been rated at 8.33/10 (previous run: 10.00/10, -1.67)

So here you see pylint points your attention to implicit return values from some path(s) in your function. Note that some of pylint's reports (the ones I disabled for instance) may generate "noise" rather than be helpful). Still, using this tool (and mypy and others) may sure help you

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87