Python · Stage 6 – Reusable Code · Lesson 36 of 50

Local and Global Scope

Understand where a variable name can be used.

def greet():
    message = "Hello"
    print(message)

greet()
Line-by-line explanation
  1. The function is defined.
  2. message is created locally inside it.
  3. The function can display message.
  4. The call runs the function.

Prefer parameters and return values over changing global variables. They make each function’s inputs and outputs visible.

Tiny Practice

Identify the local variable and display it inside the function.

Starter template

def show():
    word = "local"
    CHANGE_ME

show()
Line-by-line explanation
  1. Word is created inside show.
  2. The missing line is inside the function.
Hint
  1. Use print.
  2. Pass word without quotes.
  3. Keep indentation.
Show Solution
def show():
    word = "local"
    print(word)

show()
Line-by-line explanation
  1. Word is local to show.
  2. It is displayed while in scope.
  3. The call runs the function.