11. Scope
Variables created inside a function are local: they exist only while the function runs and cannot be read outside it. Variables created at the top level of the program are global:
- Reading a global inside a function works without any keyword.
- Assigning to a name inside a function creates a local variable, even if a global with the same name exists.
global nameinside the function makes an assignment change the global variable instead.- A local variable disappears when the function returns.
Coming from JavaScript? There is no hoisting and no let/const block scope: a name assigned inside a function is local to that function. Reading a global works, but assigning to it needs global.
Use a local variable
Define calculate() that creates the local variable result = 10 + 5 and returns it. Print calculate().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A local variable cannot be read outside
Define set_value() that creates the local variable value = 42 and returns nothing. Call set_value(), then print value outside the function. Accessing it outside its function must stop the program with:
Create a free account to save your progress and unlock chapter 2.
Read a global variable
Create the global variable city = "Paris". Define show_city() that prints city without creating a local variable. Call show_city().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Change a global variable
Create the global variable count = 0. Define increment() that declares global count and adds 1 to it with count += 1. Call increment(), then print count.
Print exactly:
Create a free account to save your progress and unlock chapter 2.