Class 12 Python – Functions: Scope, Parameter Passing, and Return Values
1. Functions in Python
-
A function is a block of reusable code that performs a specific task.
-
Functions help in modular programming, making code organized, readable, and maintainable.
-
Functions are defined using the
defkeyword.
2. Scope of Variables
-
Scope refers to the region of the program where a variable is accessible.
a) Local Scope
-
A local variable is defined inside a function.
-
Accessible only within that function.
-
Disappears once the function ends.
b) Global Scope
-
A global variable is defined outside all functions.
-
Accessible throughout the program, including inside functions.
-
Can be used to share data across multiple functions.
Key Points
-
If a local variable and a global variable have the same name, the local variable takes precedence inside the function.
-
Use global variables carefully to avoid unexpected results.
3. Parameter Passing
-
Parameters are inputs given to a function so it can perform its task.
a) Types of Parameters
-
Positional Parameters: Values are passed in order.
-
Keyword Parameters: Values are passed using parameter names.
-
Default Parameters: A default value is used if no argument is provided.
-
Variable-length Parameters: Function can accept any number of arguments.
Key Points
-
Parameters allow functions to be flexible and reusable.
-
Proper use of parameters avoids hard-coding values.
4. Return Values
-
Functions can return a value to the part of the program that called them.
-
If no value is returned, the function performs the task but gives nothing back.
Key Points
-
The return value can be stored in a variable for later use.
-
Functions can return multiple values simultaneously.
-
Using return values allows modular, testable, and maintainable code.
5. Summary Table
| Concept | Description |
|---|---|
| Local Variable | Defined inside a function; accessible only within it |
| Global Variable | Defined outside functions; accessible everywhere |
| Parameter | Input value provided to a function |
| Return Value | Value a function gives back to the caller |
| Flexible Functions | Use positional, keyword, default, or variable-length parameters |
6. Key Tips
-
Always use descriptive names for parameters and variables.
-
Keep global variables minimal to avoid confusion.
-
Use return values to make functions powerful and reusable.
-
Parameter passing allows customized behavior without changing function code.
0