From e05b67be6ae47691c0778c6bdcfdc2ef0dd970d3 Mon Sep 17 00:00:00 2001 From: waldek Date: Fri, 29 Oct 2021 14:01:34 +0200 Subject: [PATCH] adds scope --- learning_python3.md | 67 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/learning_python3.md b/learning_python3.md index e692174..9f4e7fe 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -584,6 +584,73 @@ bake_cake("banana") ## Variable scope +Variable scope might sounds complicated but with some examples you'll understand it in no time. +Remember variables are like unique *post-its*? +Well, variable scope is like having multiple colors for your post-its. +A yellow post-it with `name` on it is not the same as a red one with `name` on it so they can both reference **different** objects. +Scope is **where** the colors change, and this is done automatically for you in python. +It's an inherent feature of the language but the concept of scope is not unique to python, you'll find it in most modern languages. +Now, some examples. + +```python3 +total = 9000 + +def function_scope(argument_one, argument_two): + print("inside the function", argument_one, argument_two) + total = argument_one + argument_two + print("inside the function", total) + + +function_scope(300, 400) +print("outside the function", total) +``` + +Here `total` outside of the function references a different object from the `total` inside of the function. +Python is very *nice* and will try to fix some common mistakes or oversights by itself. +For example. + +```python3 +name = "Wouter" + +def function_scope(): + print("inside the function", name) + + +function_scope() +print("outside the function", name) +``` + +But we can not **modify** the referenced object from **inside** the function. +This will give an `UnboundLocalError: local variable 'name' referenced before assignment` error + +```python3 +name = "Wouter" + +def function_scope(): + print("inside the function", name) + name = "Alice" + + +function_scope() +print("outside the function", name) +``` + +There is however a handy **keyword** we can use to explicitly reference variables from the outermost scope. +This is done as follows with the `global` keyword. + +```python3 +name = "Wouter" + +def function_scope(): + global name + print("inside the function", name) + name = "Alice" + + +function_scope() +print("outside the function", name) +``` + ## Functions that *return* something TODO basic math functions