TechCoder.io / Python

Return Values & Scope

Understand how functions send data back and how variable scope works. Learn about local vs global variables.

By TechCoder TeamLast updated: 2026-10-17
In a Nutshell

Understand how functions send data back and how variable scope works. Learn about local vs global variables. This hands-on tutorial focuses on practical implementation of return values & scope concepts.

Return Values & Scope

Functions aren't just for printing things; they are for processing data. The return statement allows a function to send a result back to the caller.

The return Statement

When a function reaches a return statement, it stops executing and sends the value back.

PYTHON PLAYGROUND
⏳ Loading editor…

Returning Multiple Values

Python has a cool feature: you can return multiple values! Under the hood, Python packs them into a Tuple.

PYTHON PLAYGROUND
⏳ Loading editor…

Early Returns & Guard Clauses 🛡️

You can use multiple return statements to exit early. This pattern is called "guard clauses" and makes code more readable.

PYTHON PLAYGROUND
⏳ Loading editor…

Variable Scope: The LEGB Rule 🔍

Python searches for variables in this order:

  1. Local (inside current function)
  2. Enclosing (in outer functions)
  3. Global (module level)
  4. Built-in (Python's built-in names)
PYTHON PLAYGROUND
⏳ Loading editor…

The global Keyword

If you want to modify a global variable inside a function, you must use the global keyword.

PYTHON PLAYGROUND
⏳ Loading editor…

The nonlocal Keyword 🔗

For nested functions, use nonlocal to modify a variable in the enclosing (but not global) scope.

PYTHON PLAYGROUND
⏳ Loading editor…

AI Mentor

Assistant

Confused about "Python function return values and variable scope"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 5

What happens when a function executes 'return'?

It prints the value
It stops and sends the value back
It continues to the next line
It restarts the function

Key Takeaways

✅ return sends data back to the caller.
✅ Early returns (guard clauses) improve readability.
✅ LEGB rule: Local → Enclosing → Global → Built-in.
✅ Use nonlocal for enclosing scope, global for global scope.
✅ Use nonlocal for enclosing scope, global for global scope.

What's Next?

In the next lesson, we'll dive deeper into Closures - functions that remember their environment.

Keep coding! 🚀