runtric-logo
Python Basics 3 – Functions and ReuseScope (local/global variables) (4/6)
Chapter 4
Python Basics 3 – Functions and Reuse

Scope (local/global variables)

20 minutes read

Beginner friendly

Includes practice

Today we’ll uncover why some variables seem to “disappear” the moment a function ends, while others stick around. That invisible border is called scope. Once you grasp it, many confusing bugs suddenly make sense.

Runtic's Learning Tips

  • Think of scope visually: global variables are like hallway lamps, visible from different rooms.

  • When debugging, ask: “Where was this variable defined?”

  • Practice isolating scope mistakes—guess what will happen before running the code.

Lesson roadmap

  • Build an intuition for scope.
  • Compare global and local variables.
  • Learn the LEGB name-lookup rule.
  • Practice with short coding drills (answers not shown).
  • Summarize the big ideas so they stick.

Remember: Struggling a bit is normal. Each “aha!” actually rewires your brain — so lean into it!

Warm-up (Prediction First!)

Example Code

Interactive Code Editor
python

This won’t affect your saved progress.

Without running it, predict the two printed lines:

  • Inside → ?
  • Outside → ?

(Jot down your guess—retrieval practice boosts memory.)

What Is Scope?

Imagine your program is a house:

  • The hallway = global scope (everyone can see).
  • Each room = local scope created when a function runs (private while you're inside).
  • Leave the room, and anything you left “on the floor” vanishes.

Quick Summary

  • Global variables live in the main program body and are visible almost everywhere.

  • Local variables are created and vanish within the life of a function call.

  • Understanding scope prevents accidental overrides and confusion.

Global Variables – Living in the Hallway

Example Code

Interactive Code Editor
python

This won’t affect your saved progress.

Because language is global, any function can read it freely unless reassigned.

Local Variables – Room-Only Items

Example Code

Interactive Code Editor
python

This won’t affect your saved progress.

The variable message exists only while the function runs. It's not visible from the outside.

Writing to a Global from Inside a Function

Example Code

Interactive Code Editor
python

This won’t affect your saved progress.

Why the error?

  • Seeing counter = ..., Python assumes it's creating a local variable.
  • But it then tries to read that new local before it exists: 💥 UnboundLocalError

✅ Fix with global:

Example Code

Interactive Code Editor
python

This won’t affect your saved progress.

Style tip: Avoid overusing `global`

  • it often indicates design can be improved with return values or parameters.

How Python Looks Up Names – LEGB

  • Local — current function
  • Enclosing — any outer (nested) functions
  • Global — module level
  • Built-in — Python's core names like len, print, int

For now, focus on Local vs Global.
But know that Enclosing and Built-in finish the search path.

Practice Blocks – Your Turn

Practice Challenge

Interactive Code Editor
📝 Your Task:

You have a global variable wordset to "cat".Inside the function swap(),declare wordas global, then change its value to "dog"and print it inside the function. After calling swap(),print wordagain outside the function to confirm that the global variable was updated.

python

Use the global keyword to modify the variable word inside the function.

Quick Practice

3 minutes

Check your understanding of how Python handles variable scope inside and outside functions.

A variable created inside a `for` loop that sits inside a function is…

Which keyword lets a function assign to a global variable?

UnboundLocalError usually means:

Wrap-Up Challenge – No global Allowed

Update a counter without using global.

Practice Challenge

Interactive Code Editor
📝 Your Task:

Create a function called increment()that returns counter+1.Start with counter=0,then call increment()three times, each time reassigning the result back to counter.Finally, print the counter it should display 3.

python

Define increment() to return counter + 1, and update the global counter by reassigning after each call.

Lesson Complete!
100%
Progress
What You've Learned:
  • Functions create their own local scope—variables inside aren’t visible globally.
  • You can read global variables from inside a function, but writing to them requires the global keyword.
  • Using too many global variables can make programs fragile; aim for clear data flow with parameters and returns.
  • Python looks up names using the LEGB rule: Local, Enclosing, Global, Built-in.

Sign in to track your progress

Chapter Progress

0 secs

AI Tutor

Powered by Runtric

Solve first — tutor's here to guide.

Runtric might be wrong. Think critically.