What is a Function?
A function is a block of code that performs a specific task. We can call it whenever we need to execute that code.
How to Create a Function in Python?
We use the def keyword to define a function in Python. The function body must follow proper indentation.
For example:
def add(): # Function definition
print(10 + 15)
add() # Function calling statement
Output:
25
- We can define multiple functions in the same Python file.
- We must define a function before calling it.
- If multiple functions have the same name, the latest definition replaces the previous one.
Important: Calling a function before its definition has been executed will raise a NameError.
add() # Calling before definition
def add():
print(10 + 15)
Why Should We Learn Functions?
- Code Reusability: Write once and use multiple times.
- Easy Maintenance: Modify code in one place.
- Improves Readability: Makes code easier to understand.
- Modularity: Organizes code into smaller, manageable blocks.
- Easy Testing and Debugging: Test and debug individual functions.
Functions with Parameters and Arguments
We can pass values to a function using parameters and arguments.
- Parameters: Variables defined inside the function definition.
- Arguments: Actual values passed while calling the function.
For example:
def add(no1, no2): # Parameters
print(no1 + no2)
add(100, 200) # Arguments
Output:
300
Here, no1 and no2 are parameters, whereas 100 and 200 are arguments.
Function Overloading
Function overloading means defining multiple functions with the same name but different parameter lists.
For example, Java supports function overloading. However, Python does not support traditional function overloading.
If we define multiple functions with the same name, the latest definition replaces the previous one.
def add(no1, no2):
print(no1 + no2)
def add(no1, no2, no3):
print(no1 + no2 + no3)
add(100, 200)
Output:
TypeError: add() missing 1 required positional argument: 'no3'
Here, the second add() definition replaces the first one. Python expects three arguments but receives only two.
We can achieve similar functionality using default arguments or other techniques.
Pass Statement in Functions:
The pass statement acts as a placeholder when we don't want a function to perform any operation yet.
For example:
def log_add():
pass
Here, the function is defined successfully but does nothing when called. We can add the actual implementation later.
Return Function:
The return statement is used to send a result from a function back to the place where the function was called.
If a function does not contain a return statement, Python returns None by default.
Example:
def add_numbers(x, y):
return x + y
result = add_numbers(10, 20)
print(result)
Output:
30
Top comments (0)