Nearby lessons
69 of 159Python - Functions
- Understand what a function is and why it promotes code reusability
- Define and call functions using the def keyword
- Distinguish between built-in functions and user-defined functions
- Understand global and local variables and their scope
- Use the global keyword to modify global variables inside a function
- Use the globals() function to access and modify global variables
Introduction to Functions
While writing programs, sometimes we need to write the same group of statements again and again.
Writing the same code repeatedly is not a good programming practice because it increases the size of the program and makes maintenance difficult.
Instead of rewriting the same statements multiple times, we can group them together into a single unit and use that unit whenever required.
This single unit is called a Function.
A function allows us to write the code once and execute it many times by simply calling the function.
Definition of Function
A Function is a group of related statements that performs a specific task.
Once a function is created, it can be called whenever required without rewriting the same code.
Real-Life Example
Suppose a school management system needs to print the following message many times:
Hello Students Welcome to Python Class
Instead of writing these statements repeatedly, we can place them inside a function and call that function whenever needed.
Advantages of Functions
According to the tutorial, the main advantage of functions is Code Reusability.
Functions also provide several additional benefits.
- Code Reusability.
- Reduces duplicate code.
- Improves readability.
- Makes programs easier to maintain.
- Reduces program size.
- Makes debugging easier.
- Improves modular programming.
Code Reusability
Code Reusability means writing the code once and using it many times.
Instead of copying the same statements into different parts of the program, we simply call the function.
This saves both time and effort.
Types of Functions
Python supports two types of functions.
- Built-in Functions
- User Defined Functions
1. Built-in Functions
Functions that are already available in Python are called Built-in Functions or Predefined Functions.
These functions are automatically available after installing Python.
We do not need to write their implementation.
Common Built-in Functions
Some common built-in functions are:
id()type()input()eval()len()print()sum()max()min()
Example
2. User Defined Functions
Functions created by the programmer according to business requirements are called User Defined Functions.
These functions are written using the def keyword.
Syntax of User Defined Function
Syntax Explanation
| Part | Description |
|---|---|
def |
Keyword used to define a function. |
| function_name | Name of the function. |
| parameters | Input values accepted by the function. |
| Doc String | Description of the function. |
| statements | Task performed by the function. |
| return | Returns the result to the caller. |
The def Keyword
The def keyword is used to create a User Defined Function.
Every function definition begins with the def keyword.
Syntax
First Function Program
Understanding the Program
def wish():
Defines a function named wish().
print("Hello Good Morning")
This statement is executed whenever the function is called.
wish()
Calls the function.
Since the function is called three times, the message is printed three times.
Calling a Function
A function is executed only when it is called.
Simply defining a function does not execute it.
Syntax
Example
Important Point
Merely defining a function does not execute it.
The function body is executed only when the function is called.
Difference Between Defining and Calling a Function
| Defining Function | Calling Function |
|---|---|
| Creates the function. | Executes the function. |
Uses def. |
Uses the function name followed by parentheses. |
| Executed only once. | Can be executed any number of times. |
Introduction to Variables in Functions
Variables are used to store data in a program.
Depending on where a variable is declared, Python classifies variables into different types.
Python supports two types of variables:
- Global Variables
- Local Variables
Understanding the scope of variables is very important because it determines where a variable can be accessed and modified.
Function vs Module vs Library
Before learning Global and Local Variables, it is important to understand three related terms.
| Term | Description |
|---|---|
| Function | A group of statements written together to perform a specific task. |
| Module | A file that contains one or more functions. |
| Library | A collection of multiple related modules. |
Global Variables
The variables declared outside of every function are called Global Variables.
Global variables belong to the entire module.
Every function inside the same module can access global variables unless a local variable with the same name exists.
Characteristics of Global Variables
- Declared outside all functions.
- Accessible throughout the module.
- Can be shared by multiple functions.
- Remain available until the program finishes.
Program: Accessing a Global Variable
Understanding the Program
The variable a is declared outside every function.
Therefore, it becomes a Global Variable.
Both f1() and f2() can access the same variable.
No separate copy of the variable is created for each function.
Scope of Global Variables
| Declared Outside Function? | Accessible Inside Function? | Accessible by Multiple Functions? |
|---|---|---|
| Yes | Yes | Yes |
Local Variables
The variables declared inside a function are called Local Variables.
A local variable exists only while the function is executing.
After the function completes, the local variable is destroyed.
It cannot be accessed from outside the function in which it is declared.
Characteristics of Local Variables
- Declared inside a function.
- Accessible only inside that function.
- Cannot be accessed from outside the function.
- Created when the function starts executing.
- Destroyed after the function finishes execution.
Program: Local Variable
Understanding the Program
The variable a is created inside f1().
Therefore, it is a Local Variable.
It is available only while f1() is executing.
When f2() tries to access it, Python cannot find the variable and raises a NameError.
Lifetime of a Local Variable
| Event | Local Variable |
|---|---|
| Function starts | Created |
| Function executes | Available |
| Function ends | Destroyed |
Difference Between Global and Local Variables
| Global Variable | Local Variable |
|---|---|
| Declared outside functions. | Declared inside functions. |
| Accessible throughout the module. | Accessible only inside its function. |
| Can be shared by multiple functions. | Cannot be shared outside the function. |
| Exists throughout program execution. | Exists only while the function executes. |
Real-World Applications
- Global variables are used for application-wide configuration settings.
- Global variables can store constants shared by many functions.
- Local variables are used for temporary calculations.
- Loop counters and intermediate results are generally local variables.
- Keeping temporary values local improves program safety and readability.
The global Keyword
In the previous section, we learned that a Global Variable can be accessed inside a function.
However, if we try to modify a Global Variable directly inside a function, Python creates a new Local Variable instead of modifying the Global Variable.
To modify a Global Variable inside a function, we must use the global keyword.
The global keyword tells Python that the variable belongs to the Global Scope and not to the Local Scope.
Syntax
Syntax Explanation
| Keyword | Purpose |
|---|---|
global |
Allows a function to modify a Global Variable. |
Example 1 - Accessing a Global Variable
Explanation
The variable a is declared outside the function.
Since the function only reads the variable, the global keyword is not required.
Example 2 - Modifying Without global
Explanation
The assignment a = 20 creates a new Local Variable.
The Global Variable remains unchanged.
Therefore, the function prints 20, but outside the function the value is still 10.
Example 3 - Modifying a Global Variable
Explanation
The statement global a informs Python that the variable belongs to the Global Scope.
Now the assignment updates the original Global Variable instead of creating a Local Variable.
Therefore, both statements print 20.
Example 4 - Multiple Functions Using global
Explanation
The Global Variable count is updated every time the function is called.
Since the same Global Variable is modified, the final value becomes 3.
The globals() Function
Python provides the built-in globals() function.
This function returns a Dictionary containing all Global Variables available in the current module.
The Dictionary keys represent variable names, and the values represent the corresponding Global Variable values.
Syntax
Example 5 - Using globals()
Explanation
The globals() function returns a Dictionary.
Besides user-defined Global Variables, the Dictionary also contains several built-in objects created by Python.
For simplicity, only user-defined variables are shown in the sample output.
Example 6 - Accessing Global Variables Using globals()
Explanation
The globals() function returns a Dictionary.
Dictionary indexing can be used to access any Global Variable by its name.
Example 7 - Modifying Global Variable Using globals()
Explanation
Since globals() returns the Global Namespace Dictionary, changing its value updates the original Global Variable.
Difference Between global Keyword and globals()
| global Keyword | globals() Function |
|---|---|
| Used inside a function. | Can be used anywhere. |
| Declares a variable as Global. | Returns the Global Namespace Dictionary. |
| Mainly used to modify Global Variables. | Used to view or access all Global Variables. |
| Keyword. | Built-in Function. |
Real-World Applications
- Maintaining application-wide counters.
- Updating global configuration values.
- Managing shared application state.
- Accessing global settings across multiple functions.
- Debugging by inspecting the Global Namespace.
- A function groups related statements into a reusable unit
- Functions are defined with def and called by their name
- Built-in functions like len(), type(), max() and min() are always available
- Global variables are declared outside functions and are accessible throughout the module
- The global keyword and globals() function allow modifying global variables from inside a function