Python Python Basics (2015) Number Game App Number Game Refinement

Yao Tung Ooi
Yao Tung Ooi
13,744 Points

I'm a bit confused about calling the game() function when we are still inside the game() function... How does that work?

I'm a bit confused about calling the game() function when we are still inside the game() function... How does that work?

Will all the variables be reset again? As if we are calling it the first time?

1 Answer

Larry McGee
Larry McGee
3,955 Points

When a function calls itself this is called "recursion". This technique is usually introduced at a more advanced stage of a programming class.

As to why he used recursion in this beginner level program, my guess would be that he is so use to using this technique that he didn't realize he used it until after recording the lesson.

When you make a recursive call the computer saves the current state (all variables and their values) of the current function call and then creates a new instance of the function and begins execution with it's own set of variables. When that instance completes execution the program returns to the point where the recursive call was made and continues execution with the previously saved state.

If you do a quick search for "how does recursion work" you will find several visual tutorials that explain the technique and how it works.