Lesson 4.2: Return Statement and Scope of Variables
Introduction:
In Python, understanding the return statement and variable scope is crucial for writing organized and bug-free code. The return statement allows functions to send results back to the caller, while variable scope determines where variables can be accessed within a program.
1. The Return Statement:
-
The
returnstatement sends a value from a function back to the caller. -
A function without
returnreturnsNoneby default.
Example – Using return:
Output:
Key Points:
-
You can return multiple values as a tuple.
2. Variable Scope in Python:
-
Scope determines the visibility and lifetime of a variable.
Types of Scope:
-
Local Variables:
-
Defined inside a function
-
Accessible only within that function
-
-
Global Variables:
-
Defined outside any function
-
Accessible anywhere in the program
-
-
Global Keyword:
-
Allows modifying global variables inside a function
-
Practical Tips:
-
Prefer using local variables to avoid unintended side-effects
-
Use the
returnstatement to pass results instead of relying on global variables -
Keep functions self-contained and modular
Learning Outcome of This Lesson:
-
Understand the purpose and use of the
returnstatement -
Return single or multiple values from functions
-
Distinguish between local and global variables
-
Apply variable scope rules to write cleaner, bug-free code
-
Modify global variables safely using the
globalkeyword
