Function Call Stack

From Knowledge Kitchen
Jump to navigation Jump to search


Function Stack example

This example exhibits the nature of function calls, and shows how they stack up.

Code

#this program shows the stacking nature of function calls
#the program starts in global scope, moves to the local scope of the doSomething  function, and then moves to the local scope of the doAnotherThing function...
#then returns back down the stack of function calls

def doAnotherThing():
    print("Entering local scope of the doAnotherThing function...")

def doSomething():
    print("Entering local scope of the doSomething function...")
    doAnotherThing()
    print("Returning to local scope of doSomething...")


print("Starting out in global scope")
doSomething()
print("Returning to global scope")

Flow chart

A flow diagram showing the function calls and changes in scope:

Function scope flow chart example.png

A more traditional stack diagram:

Function scope stack diagram example.png

Toyota Camry Hovercraft example

This example reinforces the usage of functions, while introducing a few new concepts, including if statements and while loops, which we will cover in detail later.

Code

def turn(direction):
    global currentStreet
    global currentAvenue
    
    #local scope of function
    if direction == "forward":
        print("You said forward!")
        currentStreet = currentStreet + 1

    if direction == "backward":
        print("You said backward")
        currentStreet = currentStreet - 1

    if direction == "left":
        print("You said left")
        currentAvenue = currentAvenue + 1

    if direction == "right":
        print("You said right")
        currentAvenue = currentAvenue - 1

#global scope
car = "Toyota Camry Hovercraft"

currentAvenue = 5
currentStreet = 4

print("Your " + car + " is always facing north... starting at",
      currentStreet, "street and",
      currentAvenue, "avenue")

#do this over and over
while True:
    response = input("What would you like to do?")

    turn(response)

    print("Your", car, "is now at",
          currentStreet, "street and",
          currentAvenue, "avenue")

Flow diagram

Toyota camry hovercraft program flow chart.png


What links here