ByteBoard Notes Notes

Show the difference between local and global variables

Computer Science XII · Experiment 04 of 29 · Python

12-CSPython programs
Expt. No.04
Page No.8

Local and global scope

Aim

To write a Python program that shows how a local variable hides a global variable of the same name, and how the global keyword lets a function change a global variable.

Concepts used

Algorithm

  1. Create a global variable count = 10.
  2. In show_local(), create a local count = 5 and print it.
  3. In change_global(), declare global count and add 1 to it.
  4. Print count before and after calling each function.

Program

# Local and global variables count = 10                     # global variable def show_local():    count = 5                  # local variable, hides the global one    print("Inside show_local    : count =", count) def change_global():    global count               # use the global variable    count = count + 1    print("Inside change_global : count =", count) print("Before the calls     : count =", count)show_local()print("After show_local     : count =", count)change_global()print("After change_global  : count =", count)

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python local_and_global_scope.py
Before the calls : count = 10 Inside show_local : count = 5 After show_local : count = 10 Inside change_global : count = 11 After change_global : count = 11

✓ Printed by running this program, not typed by hand.

Result

The global count stayed 10 after show_local(), which only changed its own local copy (5). change_global() used the global keyword, so the global count became 11 and stayed 11 after the call.

Viva voce: what the examiner may ask

01What is the scope of a variable?

The part of the program where the variable can be used. A local variable exists only inside its function; a global one is visible everywhere in the file.

02What does the global keyword do?

It tells Python that the name inside the function refers to the global variable, so assigning to it changes the global value.

03What happens if count = count + 1 is written without global?

Python treats count as local and raises UnboundLocalError, because the local count has no value yet.

Variations for the lab test

  1. Add a function that only reads the global count without global and check whether it works.
  2. Change a global list inside a function with append() and explain why global is not needed.
  3. Create a variable inside a function and try to print it outside.
! Common mistake Expecting show_local() to change the global count. Assigning to a name inside a function creates a new local variable.
Back to the 12-CS index