{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sub1 g: 3\n",
      "sub1 a: 5\n",
      "sub1 b: 7\n",
      "sub2 g: 3\n",
      "sub2 c: 9\n",
      "sub3 g: 11\n",
      "sub3 c: 9\n",
      "sub1: 3\n"
     ]
    }
   ],
   "source": [
    "g = 3                     # creates a global for referencing, since outside\n",
    "def sub1():\n",
    "    a = 5                 # creates a local\n",
    "    b = 7\n",
    "    print(\"sub1 g:\", g)\n",
    "    print(\"sub1 a:\", a)\n",
    "    print(\"sub1 b:\", b)\n",
    "    def sub2():\n",
    "        global g           # allow both referencing and assign to global\n",
    "        c = 9           \n",
    "        print(\"sub2 g:\", g)\n",
    "        print(\"sub2 c:\", c)\n",
    "        def sub3():\n",
    "                nonlocal c          # nonlocal can access parent c\n",
    "                g=11                # new local\n",
    "                print(\"sub3 g:\", g)\n",
    "                print(\"sub3 c:\", c)\n",
    "        sub3()\n",
    "        \n",
    "    sub2()\n",
    "\n",
    "sub1()\n",
    "print(\"sub1:\", g)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
