
Function
- Functions are reusable blocks of code that perform a specific task.
- In Python, functions help organize code, making it more modular and readable.
- Python supports two types of functions:
- Built-in functions: Predefined by Python, such as print(), len(), etc.
- User-defined functions: Created by users to meet specific needs.
- We can create no.of functions based on your requirement.
Table of Contents
Why Functions Are Required?
Let’s consider a daily routine task, like preparing a nice cup of tea:
- Boil the water.
- Add tea powder.
- Pour in hot water.
- Add milk and sugar.
- Stir well.
- Serve in a cup.
Now, imagine if you had to explain every single step to someone every time they wanted to make coffee. It would be tiresome, right?
Instead, you can simply say, “Make me a nice cup of tea,” and they’ll know exactly what to do without having to explain all the steps every single time.
Similarly, in programming, if we have a group of statements that perform a task repeatedly, we can avoid writing the same code again and again by defining a function.
When to use?
When a block of code is required or needed multiple times, and writing it repeatedly is inefficient. Instead, define a function to encapsulate the code and call it whenever needed.
Function Terminology in Python
To understand functions more clearly, focus on these key terms:
- def keyword: Used to define a function.
- Function name: The name that identifies the function.
- Parentheses (): Used to call the function and hold parameters if required.
- Parameters: Values passed to the function (optional).
- Colon :: Marks the beginning of the function’s block of code.
- Function body: The set of statements executed by the function.
- Return type: (Optional) Specifies what value the function sends back after processing.
Function Structure
- Function Definition: The process of creating a function.
- Function Calling: Running or executing the function.
Types of Functions
By Parameters:
- Without parameters: No inputs are needed.
- With parameters: Inputs are passed to the function.
By Return Type:
- Without return statement: Functions that do not return a value.
- With return statement: Functions that return a result after performing operations.
Function Definition (creation)
- Define the Function – Use the def keyword to start creating a function.
- Function Name – Write the name of the function after def (as per identifier rules).
- Parentheses () – Include parentheses after the function name, which may contain parameters.
- Parameters: Variables that receive values when the function is called.
- Colon(:) – Place a colon after the parentheses to indicate the start of the function body.
- Function Body – Indent the next line to write the actual logic of the function, performing the desired operations.
- Return Type (optional) – The function may return a value before it ends.
Syntax:
def function_name(parameters):
"""Docstring: Describe what the function does."""
# Body of the function to perform operations
return value
Example:
# Function definition (no parameters and no return)
def greet():
print("Hello, welcome to the function!")
Function Calling
After creating a function, you must call it to execute its body. Ensure the function name matches when calling it, or you’ll encounter an error.
# Function definition (no parameters and no return)
def greet():
print("Hello, welcome to the function!")
# Function call
greet() # Output: Hello, welcome to the function!
Types of Functions
Functions can be categorized into two types based on parameters:
- Functions without Parameters: These functions do not take any input values.
- Functions with Parameters: These functions accept input values to operate on.
Functions without Parameters:
# Function definition (no parameters and no return)
def wish():
print("Good Morning!")
# Function call
wish() # Output: Good Morning!
Functions with Parameters:
# Adding two numbers
def add(a, b):
return a + b
# Function call
result = add(5, 3)
print("Sum:", result) # Output: Sum: 8
Parameters in functions are essential because they:
- Allow Data Input: You can pass different values to the function.
- Enhance Reusability: The same function can be used with various data.
- Improve Clarity: They specify what data the function needs, making the code easier to understand.
- Reduce Redundancy: One function can handle multiple tasks with different inputs, minimizing code duplication.
Note: For parameterized functions, you must provide values when calling them, or an error will occur; this doesn’t apply to variable-length argument functions, which will be discussed later.
Functions can be categorized into two types based on return:
- Functions without return
- Functions with return
What is return in Functions?
A return statement is used in functions to send value back to its caller. When a function executes a return, it exits the function and provides the specified value.
Function Without Return:
A function without a return statement performs an action, like displaying a message, but doesn’t send a value back to the caller. By default, it returns None.
# Function creation
def greet():
print("Hello, welcome!")
# Function call
call = greet()
print(call)
# Output:
Hello, welcome!
None
Function With Return
A function with a return statement provides a value back to its caller, which can be stored in a variable or used in calculations. Once the return statement is executed, the function will exits and moves to the next line of the code (outside of function).
Example 1:
# Function creation
def add(a, b):
return a + b # once function calls, function exits here
print("Executed successfully!")
# Function call
result = add(5, 3) # Output: Sum: 8
print("Sum:", result) #Output: Sum: 8
Example 2:
# Function creation
def add(a, b):
print("Before Return!")
return a + b # once function calls, function exits here
print("After Return!")
# Function call
result = add(5, 3)
print("Sum:", result)
#Output:
Before Return!
Sum: 8
Function Returning Multiple Values
A function can return more than one value in tuple format. This allows you to package related data together and return it in a single return statement.
Example:
Function Returning Two Values
def calculate_area_perimeter(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter # Returning both area and perimeter
# Function call
area, perimeter = calculate_area_perimeter(5, 3) # Tuple unpacking
print(f"Area: {area}") # Output: Area: 15
print(f"Perimeter: {perimeter}") # Output: Perimeter: 16
Function Returning Three Values
def get_statistics(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count if count > 0 else 0
return total, count, average # Returning total, count, and average
# Function call
total, count, avg = get_statistics([10, 20, 30, 40]) # Tuple unpacking
print(f"Total: {total}") # Output: Total: 100
print(f"Count: {count}") # Output: Count: 4
print(f"Average: {avg}") # Output: Average: 25.0
Difference Between print and return
- print: Outputs a value to the console but does not affect the flow of the program. It is primarily for displaying information.
- return: Exits the function and provides a value to the caller, allowing that value to be used later in the program.
Functions Calling Other Functions
In Python, you can use one function to call another function. This allows for modular code and can help break complex tasks into simpler, manageable parts. When one function calls another, it can pass arguments to it and receive values in return.
Example:
Simple Function Calls
# Function-1
def greet(name):
return f"Hello, {name}!"
# Function-2
def welcome():
message = greet("Alice") # Calling greet function
print(message)
# Function call
welcome() # Output: Hello, Alice!
Multiple Function Calls
# Function-1
def multiply(x, y):
return x * y
# Function-2
def square(n):
return multiply(n, n) # Calling multiply function to square a number
# Function call
result = square(4)
print("Square:", result) # Output: Square: 16
Calling Functions with Parameters
# Function-1
def calculate_area(length, width):
return length * width
# Function-2
def display_area(length, width):
area = calculate_area(length, width) # Calling calculate_area function
print(f"The area is {area}")
# Function call
display_area(5, 3) #Output: The area is 15
Functions Inside Other Functions
In Python, you can define or create a function inside another function. This is often useful for encapsulating functionality that is only relevant within the outer function. An inner function has access to the variables in the outer function’s scope.
Example:
Inner Function Definition
def outer_function(message):
def inner_function():
print(f"Inner Function: {message}") # Accessing outer function's variable
inner_function() # Calling the inner function
# Function call
outer_function("Hello from the outer function!")
# Output:
Inner Function: Hello from the outer function!
Inner Function with Parameters
def outer_function(x):
def inner_function(y):
return x + y # Using outer function's variable
result = inner_function(10) # Calling the inner function with an argument
print(f"Result: {result}")
# Function call
outer_function(5)
# Output:
Result: 15
Returning Inner Function
def outer_function():
def inner_function():
return "This is the inner function!"
return inner_function # Returning the inner function
# Getting the inner function
my_inner_function = outer_function()
# Calling the inner function
print(my_inner_function())
# Output:
This is the inner function!
Passing a Function as a Parameter
In Python, you can pass functions as arguments or parameters to other functions. This enables higher-order functions, which can takes other functions as input, enabling flexible and reusable code.
Example:
Passing a Function as a Parameter
def greet(name):
return f"Hello, {name}!"
def process_greeting(func, name):
# Call the passed function with the name parameter
greeting = func(name)
print(greeting)
# Function call
process_greeting(greet, "Alice")
# Output:
Hello, Alice!
Using a Function to Apply Operations
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def apply_operation(func, x, y):
result = func(x, y) # Call the passed function with x and y
return result
# Function calls
print(apply_operation(add, 5, 3)) # Output: 8
print(apply_operation(subtract, 5, 3)) # Output: 2
Assigning a Function to a Variable
def greet(name):
return f"Hello, {name}!"
# Assign the function to a variable
greeting_function = greet
# Call the function using the variable
message = greeting_function("Alice")
print(message) # Output: Hello, Alice!
Types of Parameters in functions:
- Positional Parameters
- Keyword Parameters
- Default Parameters
- Variable-Length Parameters
Positional Parameters
Values are passed to the function as the parameters or arguments order they are defined .
def add(a, b):
return a + b
result = add(3, 5) # a=3, b=5
Keyword Parameters
Values are passed to the function by explicitly naming the parameters. This allows you to provide parameters or arguments in any order.
def greet(name, message):
return f"{message}, {name}!"
result = greet(message="Good morning", name="Alice")
Default Parameters
These parameters have default values assigned. If no argument or parameter is provided for that parameter, the default value is used.
def greet(name, message="Hello"):
return f"{message}, {name}!"
result1 = greet("Alice") # Uses default message
result2 = greet("Bob", "Hi") # Overrides default message
Variable-Length Parameters
Sometimes you may want to pass a variable number of parameters or arguments to a function. This can be achieved using *args for non-keyword arguments and **kwargs for keyword arguments.
Example: *args
def add(*args):
return sum(args)
result = add(1, 2, 3, 4) # Outputs: 10
Example: **kwargs
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
Lambda Function (Anonymous Function)
- A lambda function is a small, anonymous function defined without a name using the lambda keyword.
- It is primarily used for short, simple tasks and is often utilized within functions like map(), filter(), and reduce().
Syntax: lambda arguments: expression
A lambda function can accept multiple parameters but consists of only a single expression.
Example:
# Lambda to add 10 to a number
add_10 = lambda x: x + 10
print(add_10(5)) # Output: 15
Using Lambda with map(), filter(), and reduce()
map() Function:
- The map() function applies a lambda or function to every item in an iterable (like a list).
Syntax: map(function, Iterable)
Example:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
filter() Function:
- The filter() function filters items in an iterable based on a condition.
Syntax: filter(function, iterable)
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8]
reduce() Function (from functools module):
- The reduce() function applies a function cumulatively to the items of an Iterable, reducing it to a single value.
Syntax:
from functools import reduce
reduce(function, iterable)
Example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120
Conclusion
These common functions provide essential operations for handling dictionaries in Python. While len(), min(), max(), and sorted() can be effectively used, reversed() is not applicable due to the unordered nature of dictionaries.
Check out our full Python guide here. : Learn From KSR Datavizon | Explore and Read Our Blogs Written By Our Industry Expert
Knowledge Check
Related Article No.4
Check out our Trending Courses Demo Playlist
Data Analytics with Power Bi and Fabric |
Could Data Engineer |
Data Analytics With Power Bi Fabic |
AWS Data Engineering with Snowflake |
Azure Data Engineering |
Azure & Fabric for Power bi |
Full Stack Power Bi |
Kick Start Your Career With Our Data Job
Social Media channels
► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id16110
Most Commented