adds scope
This commit is contained in:
parent
6c65fe7156
commit
e05b67be6a
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue