Skip to content
CodeNest

Functions and ErrorsLesson 14 of 1913 min

Scope and Modules

Where variables live, and how to split a program across files and reuse the standard library.

By the end you will be able to

  • Explain local versus global scope
  • Import modules and specific names from them
  • Use the __name__ guard in a script

Scope

Variables created inside a function are local to it. They exist while the call runs and vanish when it returns — which is exactly what you want, since it means two functions can safely use the same variable name.

Python
Output
inside: 5
outside: 100
— expected output; press Run to execute it yourself

A function can read a global it never assigns to. But the moment a name is assigned anywhere in the body, Python treats it as local throughout — which produces a surprising error.

Python
Output
can read the global: 0
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
— expected output; press Run to execute it yourself

Modules

A module is just a .py file. import makes its contents available. Python ships with a large standard library, all of it importable with no installation.

Python
Output
12.0
3.141592653589793
3 4
09 August 2026
— expected output; press Run to execute it yourself

You can also import specific names to skip the module prefix. Run this one a few times — the results change, so there is no fixed expected output to show you.

Python
Output

Press Run to execute this code.

Your own modules

If you save this as tools.py:

def shout(text):
    return text.upper() + "!"

then a file beside it can use import tools and call tools.shout("hi"), or from tools import shout and call shout("hi") directly.

The __name__ guard

When a file is run directly, Python sets its __name__ to "__main__". When it is imported, __name__ is the module's name instead. This line is how a file can be both a reusable module and a runnable script:

if __name__ == "__main__":
    main()

Without it, importing the file would execute its demo code as a side effect.

Exercise

Write circle_area(radius) that uses math.pi to return the area (π r²), rounded to 2 decimals. Remember the import.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.A variable assigned inside a function is visible where?
  2. 2.What does from math import sqrt let you write?