Lesson 45: Local or global
Where can a variable be used?
- The scope of a variable is the part of the program that can use it.
- A global variable is made outside all functions. Every part of the program can use and change it.
- A local variable is made inside a function. Only that function can use it, and it is new each time the function runs.
Words for this lesson
| Word | Meaning |
|---|---|
| scope | where in the program a variable can be used |
| global variable | can be used anywhere in the program |
| local variable | can be used only inside its function |
Which one to use?
| Global | Local | |
|---|---|---|
| Made | outside functions | inside a function |
| Scope | the whole program | that function only |
| Changed by | any part of the program | only its function |
| Good for | a value the whole program shares (battery) | working values (a count for one call) |
- Use local variables when you can: another part of the program cannot change them by mistake.
- In Python, a function that changes a global variable needs the line
global battery.
In the exam
- 0478/23/O/N/23 Q7: describe two differences between local and global variables. Mark scheme: a local variable's scope is a defined block of code (a procedure or function), a global variable's scope is the whole program; a local variable's value cannot be changed elsewhere in the program, a global variable's value can be changed anywhere in the program.
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
battery is a global variable: it is made outside every function, so the whole program can use it. Each step() drives 100 mm and uses 2 % of the battery. Press Run: Python stops with an error, because a function that changes a global variable must say so first. Add the line global battery at the top of step. The robot then prints how much battery is left.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
count_red(steps) drives along a row and counts the red tiles. It uses the global red, so row 2 also counts the tiles from row 1: the numbers are wrong. Make red a local variable: delete the global line and the line red = 0 above the function, and start red = 0 inside the function. Each call then starts from 0.
คลิก Run เพื่อดูผลลัพธ์ที่นี่