Lesson 22 of 60
โฎPrev Nextโฏ

PY-101 ยท Functions

Scope

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

22of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    Scope is where a variable can be seen. Variables created inside a function are local: they exist only while the function runs. Variables created outside are global; functions can read them, but assigning to the name inside a function creates a new local variable instead.

    • Tell local from global variables
    • Know why a function cannot see another function's variables
    • Prefer return over global

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Scope, running
    1. bonus = 100
    2. def salary(base):
    3. total = base + bonus
    4. return total
    5. pay = salary(5000)
    6. print("Pay:", pay)
    7. print("Bonus is still", bonus)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemTwo functions both use a variable called total. If they shared it, one would wreck the other's maths. Scope keeps each function's workings private.
    2. The Python ideax = 1 # globalScope is where a variable can be seen.
    3. In real lifeLarge codebases avoid global variables because any function could change them, making bugs very hard to trace.

    Start with a question

    Two functions both use a variable called total. If they shared it, one would wreck the other's maths. Scope keeps each function's workings private.

    Most confusing beginner bugs with functions are scope bugs. Understanding it makes functions predictable.

    Explain it like I'm 10

    Each function has its own desk. What it writes on its desk stays there. Everyone can read the noticeboard on the wall (globals), but writing on your desk does not change the noticeboard.

    The technical explanation

    A variable assigned inside a function is local. It disappears when the function returns.

    A function can read a global variable, but x = ... inside the function makes a new local x.

    The global keyword lets a function change a global, but it makes code harder to follow. Returning values is cleaner.

    Syntax

    x = 1          # global
    
    def f():
        y = 2      # local
        return x + y

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Large codebases avoid global variables because any function could change them, making bugs very hard to trace.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Where does a local variable exist?
    2. 2. Can a function read a global variable?
    3. 3. x = 1; def f(): x = 2. After f(), what is x outside?
    4. 4. What happens to locals when a function returns?
    5. 5. Cleanest way to let a function change a value?

    Questions people ask

    What is the LEGB rule in Python?

    The order Python looks for a name: Local, Enclosing function, Global, Built-in. The first place that has the name wins.

    Why is using global bad?

    Any function could change the value, so bugs are hard to trace. Passing values in and returning them out keeps functions independent and testable.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner What is the LEGB rule in Python?

    The order Python looks for a name: Local, Enclosing function, Global, Built-in. The first place that has the name wins.

    beginner Why is using global bad?

    Any function could change the value, so bugs are hard to trace. Passing values in and returning them out keeps functions independent and testable.

    intermediate Where does a local variable exist?

    Only inside its function. Locals live inside the function call.

    intermediate Can a function read a global variable?

    Yes. Reading works without any keyword.

    Quick revision

    Remember

    • Tell local from global variables
    • Know why a function cannot see another function's variables
    • Prefer return over global
    • If you need a function to change a value, return the new value and assign it outside: score = add_points(score, 10). Avoid the global keyword.

    Syntax

    x = 1          # global
    
    def f():
        y = 2      # local
        return x + y

    Official documentation