Alic
Alic

Reputation: 648

Python does not return value but print value

I am new to python, and relative new to recursive. Below is my code,

def day_add(day,delta):
    if day_num(day) + delta >= 7:
        newNum = delta - 7
        day_add(day,newNum)
        return day_add(day,newNum)
    else:
        day = day_name(delta+day_num(day))
        return day

if I have the line

return day_add(day,newNum)

the function behaves correctly and return the correct value. However, if I do not have this line, but have

print(day)

the function may return None if it goes to recursion, but print the correct value.

So why do I need to return the function if I have recursion?

Upvotes: 2

Views: 2513

Answers (4)

kdragger
kdragger

Reputation: 446

print displays to the screen. or, in other words, it gives the value to the you (the user). but in this case, your code needs the answer to the smaller problem. it can't read what is on the screen. it needs to the value from the function it calls -- even if in this case it calls itself. by 'return'ing the value it passes the information back up the chain.

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120578

There are two paths through your function. One that returns day, and one that re-calls your function with a new set of arguments.

The else clause is the "uninteresting" one. It just returns a fixed value, so no mystery there.

The if clause is more "interesting". It has the effect of breaking up a computation into a series of linked steps. A little piece of the computation is done at each step, and handed on down the line until the computation is complete. The else branch decides when the compuation is complete by returning the final value. This value gets handed back up the line until the first recursive call finally returns it from your function at the top level.

So if wasn't for the recursive returns, the final value couldn't get passed back up the line. With no explicit return statements, None would be returned by default.

Putting print(day) in the else clause allows you to "peek" at the final value before the recursive calls start to return. The computation steps are all complete at that stage - the only thing left to do is to retrace those steps and exit from the top-level function.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

Recursion is a method where the solution to a problem depends on solutions to smaller instances of the same problem... - Wikipedia

So, trying to solve the "big" problem, you will use the same method but in a "smaller" problem. In other words, you will need the answer from the "smaller" problem in order to solve the "big" one. Therefore, you must return that result because if not, you will just print it, and it couldn't be used to solve the "bigger" problem.

Upvotes: 3

Scott Hunter
Scott Hunter

Reputation: 49803

If you don't say to return something, it won't, recursive or not.

Upvotes: 0

Related Questions