Concept
Variable Scope: Local vs Global (`global` keyword)
Variables created inside a function are local to it. To modify a top-level global variable from inside, declare `global var_name`.
python
score = 0 # Global
def add_point():
global score
score += 1
add_point()
print(score) # 1
# 97. Variable Scope: Local vs Global (`global` keyword) Variables created inside a function are local to it. To modify a top-level global variable from inside, declare `global var_name`: ```python score = 0 # Global def add_point(): global score score += 1 add_point() print(score) # 1 ``` Engineering advice: Avoid `global` in large projects. Passing variables into functions as arguments and returning updated values makes your code testable and predictable.
Checkpoint
What happens if you assign to a variable inside a function without the `global` keyword?
Practice
Modify the global variable `clicks = 0` inside a function `tap()` by declaring `global clicks` and adding 1. Call `tap()` and print `clicks`.
01
Tap code blocks below to assemble
Available Blocks