70 likes | 155 Views
Call Stacks, Arguments and Returns. And a bit about Recursion. Functions can call other functions!. It is a natural tendency to break a big problem up into smaller problems
E N D
Call Stacks, Arguments and Returns And a bit about Recursion
Functions can call other functions! • It is a natural tendency to break a big problem up into smaller problems • This can be repeated several times – funA can be broken up into funA1 and funA2 and funA3, which can be broken into funA11 and funA12 and so on • The execution proceeds just as in other examples of function calls. • The interpreter keeps track of all these function calls using a data structure called a “call stack”.
More semantics - Call stacks (stack frames) • To keep track of all the activity involved in a function call, the interpreter uses a data structure called a “call stack” • It is a stack of records, each record is about a function call. • When a function call is made, a record of that fact is put on top of the call stack. That indicates that that function is the one executing. • When a function call is finished and is ready to return, its record is removed from the top of the stack to say it is no longer the one running. The record underneath that is the one belonging to the function which called.
More semantics – Arguments and Parameters • Parameters are named in the def statement (can only be identifiers) • They are placeholders, waiting to be filled in when the function runs • There can be any number of parameters (but don’t go overboard! more than 10 is excessive) • Arguments are named in the function call • Arguments have values which are copied to the parameters • Arguments can be identifiers, expressions, constants • The number of arguments must match the number of parameters • The names of arguments do NOT have to match the names of the parameters • The types of arguments and parameters should match or at least be similar
The return statement • The return statement tells Python that the execution of the current function (the function that the return statement is in) is done and that control passes back to the function which called it • The return statement can have nothing after the keyword, in which case Python returns the special value None • Or the return statement can have one or more expressions after the keyword (yes, a Python function can return multiple values!) • When the return statement is executed, the function is finished – therefore, do NOT put code after a return statement, it will never execute!
Recursion • Functions can call themselves! That is called Recursion. • See chapter 12 for details. • Recursion is a powerful technique but must be written carefully or it will cause infinite loops. • Don’t worry about recursion until it is covered in class