0
def nat_fn1(k):
  if k == 0:
    return 1
  elif k%2 == 0:
    return 2
  else:
    return nat_fn1 (k-1)

I first tried nat_fn1(5) and I got an answer of 2. This was expected. Then I tried the same code without return, I got a value of None, this was expected too. So applying the same concept, I tried this code :

def process_strings(s,t):
   if s == "":
      if not(t== ""):
         print(t)
   else:
      print("{0}{1}".format(s[0],t[0]))
      process_strings(s[1:], t[1:])

I tried process_strings("cat","dog"), expecting None as there is no return in the recursion. However, I still got an answer of :

cd
ao
tg

I understand how it got these values. But there's no return statement. Why is this working?

martineau
  • 119,623
  • 25
  • 170
  • 301
Compsci
  • 9
  • 3
  • 1
    The function **did** return None – OneCricketeer Jun 18 '17 at 03:06
  • Your just printing values, the function isn't returning them. – Spencer Wieczorek Jun 18 '17 at 03:07
  • I don't quite understand. Sorry I'm new to Python. So what's happening when I do recursive without return? Does it still recurse or stop before recursing? – Compsci Jun 18 '17 at 03:15
  • 1
    The function runs regardless of its return value (even None). That means that the printing is executed and the line calling the same function is also executed. – zondo Jun 18 '17 at 03:21
  • Zondo, using the same logic, I tried nat_fn1 (5) to the first program without the return. so this program recurses, can runs again as nat_fn1(4), thus 4 % 2 == 0 should return 2. However, it doesnt. Why? – Compsci Jun 18 '17 at 03:26
  • Each function will be called. The one that results in 1 or 2 will not do anything with that information (I.e. no return) so you won't *see* the result, but it is calculated. You can verify that by printing it ;) – zondo Jun 18 '17 at 03:32
  • Here's a tip. `print(process_strings("cat","dog"))`... That does print None as well as the other output. Meanwhile, `print(nat_fn1(5))` only outputs 2. You say you "apply the same concept", but you really didn't because your other function doesn't properly return anything. It's also unclear if you are wanting to return a list or a string – OneCricketeer Jun 18 '17 at 04:52

1 Answers1

1

What you get is not the return value, but the output of print statement.
If you run your code interactively in interactive prompt, it will echo the return value.

But if you run it in a file, it won't do that automatically. If you don't print the return value exactly, it will ignore the return value and output nothing.

zhenguoli
  • 2,268
  • 1
  • 14
  • 31