|
301 | 301 | "<!-- using Table Style for this -->\n",
|
302 | 302 | "| *1. Arithmetic operators* | \n",
|
303 | 303 | "|:--:| \n",
|
304 |
| - "| |\n", |
| 304 | + "|  |\n", |
305 | 305 | "\n",
|
306 | 306 | "\n",
|
307 | 307 | "| *2. Assignment Operators* | \n",
|
|
415 | 415 | "- These different namespaces are isolated. Hence, the same name that may exist in different modules does not collide.\n",
|
416 | 416 | "- Modules can have various functions and classes. \n",
|
417 | 417 | "\n",
|
418 |
| - "`Local namespace`\n", |
| 418 | + "**`Local namespace`**\n", |
419 | 419 | "- A local namespace is created when a function is called, which has all the names defined in it.\n",
|
420 | 420 | "- Similar is the case with class.\n",
|
421 | 421 | "\n",
|
| 422 | + "**`Python Nonlocal Variables`**\n", |
| 423 | + "\n", |
| 424 | + "- In Python, nonlocal variables are used in nested functions whose local scope is not defined. \n", |
| 425 | + " - This means that the variable can be neither in the local nor the global scope.\n", |
| 426 | + "- We use the nonlocal keyword to create nonlocal variables.\n", |
| 427 | + "\n", |
422 | 428 | "## <a id='toc6_1_'></a>[Python Variable Scope << Namespaces >>](#toc0_)\n",
|
423 | 429 | "**When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace.**"
|
424 | 430 | ]
|
|
463 | 469 | "outer_function()"
|
464 | 470 | ]
|
465 | 471 | },
|
| 472 | + { |
| 473 | + "cell_type": "code", |
| 474 | + "execution_count": 1, |
| 475 | + "metadata": {}, |
| 476 | + "outputs": [ |
| 477 | + { |
| 478 | + "name": "stdout", |
| 479 | + "output_type": "stream", |
| 480 | + "text": [ |
| 481 | + "inner: nonlocal\n", |
| 482 | + "outer: nonlocal\n" |
| 483 | + ] |
| 484 | + } |
| 485 | + ], |
| 486 | + "source": [ |
| 487 | + "##################### Nonlocal NameSpace #######\n", |
| 488 | + "# outside function \n", |
| 489 | + "def outer():\n", |
| 490 | + " message = 'local'\n", |
| 491 | + "\n", |
| 492 | + " # nested function \n", |
| 493 | + " def inner():\n", |
| 494 | + "\n", |
| 495 | + " # declare nonlocal variable\n", |
| 496 | + " nonlocal message\n", |
| 497 | + "\n", |
| 498 | + " message = 'nonlocal'\n", |
| 499 | + " print(\"inner:\", message)\n", |
| 500 | + "\n", |
| 501 | + " inner()\n", |
| 502 | + " print(\"outer:\", message)\n", |
| 503 | + "\n", |
| 504 | + "outer()" |
| 505 | + ] |
| 506 | + }, |
466 | 507 | {
|
467 | 508 | "cell_type": "markdown",
|
468 | 509 | "metadata": {},
|
|
0 commit comments