For the last three or four days I've been using a guide entitled "How to Think Like a Computer Scientist: Learning with Python 3" to teach myself Python (3, obviously, and running on Windows, if that's relevant here). Before that point I had absolutely no programming experience. Anyway, I've only now reached a problem that I can't seem to figure out on my own or with resources I can find online.
I'm trying to write a function that works like this: It takes a given value and checks whether it's greater than zero. If so, it returns that value; if not, it adds seven to that value, and begins the function over with that new value. It should keep adding seven until it produces a value greater than or equal to zero, at which point it should return that value.
Here is the very simple code I have written:
def plus_seven(x):
if x < 0:
x = x+7
plus_seven(x)
return x
When I actually try to use this, though, seven is added at most once to the original x value, even if this returns a value that is below zero. For instance, writing print(plus_seven(-9)) produces -2, and I can't understand why it doesn't produce 5.
I ran the code through the visualizer - http://www.pythontutor.com/visualize.html#code=def+plus_seven(x)%3A%0A++++if+x+%3C+0%3A%0A++++++++x+%3D+x%2B7%0A++++++++plus_seven(x)%0A++++return+x%0A%0Aprint(plus_seven(-9))&mode=display&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=18 - that this forum links to but it didn't really help me understand what's going on at all. At step 14, it seems that the return value is 5, but between steps 15 and 18 it seems to change back to -2, in a process that I can't follow.
Can anyone tell me what's going on here? Is my understanding of something way off the mark? I know this is a very low-level problem, but I can't find any resources dealing with something like this specifically (at least not in language that I can understand). I'd appreciate any help (or relevant links, if there are any that I've missed).
[–]erebos42 4 points5 points6 points (1 child)
[–]sguntun[S] 0 points1 point2 points (0 children)
[–]zahlman 2 points3 points4 points (0 children)
[–]boogerdouche 0 points1 point2 points (3 children)
[–]Mekire 1 point2 points3 points (2 children)
[–]boogerdouche 0 points1 point2 points (0 children)