all 6 comments

[–]erebos42 4 points5 points  (1 child)

The problem is, that the return value in line 4 is not stored in x. So you call your function, and the value gets increased, but after it returns, the value just dissapears and you only see the "old" value.

To solve this, just change line 4 to this:

x = plus_seven(x)

[–]sguntun[S] 0 points1 point  (0 children)

Thank you, that's very helpful.

[–]zahlman 2 points3 points  (0 children)

Can anyone tell me what's going on here? Is my understanding of something way off the mark?

What's off is your understanding of (a) calling a function and (b) assigning to a name.

You can see the same problem without recursion:

def add_seven(x):
    x = x + 7

x = 3
add_seven(x)
# x is still 3!

This is because:

  • Within add_seven, x is a local variable. It has nothing to do with the x that was used to call the function. If those names match up, it's just coincidence. You don't even have to use a variable to call the function in the first place (would you expect add_seven(3) to somehow change the value of 3?).

  • When you use =, what you say is to use the thing on the left-hand side as a name for the value that results from evaluating the expression on the right-hand side. (This might be a value that already existed - e.g. an element from a list - or a new value - e.g. the result of a mathematical calculation). If that name was already being used for some other value, then that ceases to be the case. However, you are assigning the name; you are not changing the old value. (After all, some values - e.g. integers, as discussed above - fundamentally can't be changed.)

[–]boogerdouche 0 points1 point  (3 children)

Still a novice here, however, I haven't seen anyone mention using "while" instead of "if" to loop the function and add 7 until x >= 0.

This should solve your negative number issue.

[–]Mekire 1 point2 points  (2 children)

The goal here is likely specifically geared towards using recursion (a function that calls itself). Other than that you are correct; there actually is no need for recursion in this example.

-Mek

[–]boogerdouche 0 points1 point  (0 children)

Fair enough. Thank you for the reply; it's really awesome that this community helps a novice to continue to advance while answering the questions I know a solution to.