Variable Scope
Local and Global Scope
Part of: Variables, Lists & Procedures
When you define variables inside procedures, where do they live, and who can see them? The answer is scope : the region of a program where a variable name is valid. Getting scope right is what makes procedures safe, reusable building blocks. Local variables A variable created inside a procedure is local to that procedure. It is born when the call starts and disappears when the call ends. Code outside cannot see it. Parameters are local too: price exists only during the call. This isolation is a feature, two procedures can both use a variable named total without interfering, because each total lives in its own scope. Global variables A variable defined at the top level of the program is global . A procedure can read a global value, but as soon as you assign to that name anywhere inside the procedure, Python treats the name as local for the entire body. So the line below tries to read a local count that has not been given a value yet, and Python raises an UnboundLocalError: Because of this, the clean style, and the one AP CSP teaches, is to pass values in as parameters and return results out , rather than reaching for globals. Why isolation matters Consider two procedures that each l
Challenge: Countdown Procedure