Definition of Function in Python

  • A function is a block of reusable code that performs a specific task. 
  • Functions are essential for writing efficient, modular, and maintainable Python code. They make programs more structured, easier to debug, and reusable, which is crucial for both small scripts and large software projects.

Characteristics of Function in Python

  • Functions are used to break down a program into smaller, manageable pieces.
  • A user-defined function in Python is defined using the def keyword, followed by the function name, parentheses (which may contain parameters), and a colon (:).
  • The code block inside the function in Python must be properly indented.
  • A function can return(optional) a value using the return keyword. This allows the result/output of the function to be used elsewhere in the program.
  • Functions are essential in Python for creating modular, reusable, and organizing the code.

Syntax of Function in Python

def function_name(parameters):
    # Code block
    statement 1
    statement 2
.
.
.
    statement n
    return result        # return statement is Optional 

Example of Function in Python

def msg(name):
    print(f“Hello, {name}!”)

msg(“India”)     # Calling the function
Output:
Hello, India

Types of Functions in Python

1. Built-in Functions/Library Functions
  • These are pre-defined functions that come with Python and can be used directly.
  • These functions are already provided by Python in ready-made form; hence, we don’t need to define them ourselves.
  • They perform common tasks such as data type conversion, mathematical operations, and many more.
  • For example:-
    • print(): This function prints the output to the console.
    • len(): This function returns the length of an object.
    • max(): This function returns the largest item from an iterable.
    • min(): This function returns the smallest item from an iterable.
    • sum(): This function sums up elements of an iterable.
print(len(“Hello”))     # Output: 5
print(max([1, 2, 3]))    # Output: 3
print(sum([1, 2, 3, 4]))       # Output: 10
2. User-defined Functions
  • These are functions defined by the programmer to perform specific tasks.
  • These are customized functions that are created/defined by users according to the needs of the def keyword.
  • We can define these functions to perform specific tasks in our program.
  • These functions are of the following types –
    • No Argument No Return
      • Example:
def msg():
    print(“Hello India”)
    #print(f“Hello India”)

msg() # Calling the function
Output:
Hello, India
    • No Argument With Return
      • Example:
def add():
    a=10
    b=40
return a + b

result = add()
print(“The addition output is = “,result)
Output:
The addition output is =  50
    • With Argument No Return
      • Example:
def msg(name):
print(f“Hello, {name}!”)
msg(“India”)     # Calling the function
Output:
Hello, India
    • With Argument With Return
      • Example:
def add(a, b):
    return a + b

result = add(30, 40)
print(“The addition output is = “,result)
Output:
The addition output is =  70
——————  OR  ——————-
def msg(name):
return f“Hello, {name}!”

# Calling the function
print(msg(“India”))
Output:
Hello, India!
3. Parameterized and Non-Parameterized Functions
Parameterized Functions
    • These functions accept arguments when called.
    • For example –
def add(a, b):
return a + b
print(add(2, 3))  # Output: 5
Non-Parameterized Functions
    • These functions don’t accept any arguments.
    • For example –
def msg():
    print(“Hello India!”)
msg()  # Output: Hello India!
4. High-Order Functions
  • These are functions that can take other functions as arguments or return them as results.
  • Some built-in functions like map(), filter(), and reduce() support this type of function.
  • For example – 
# Using map
numbers = [1, 2, 3, 4]
square = list(map(lambda x: x ** 2, numbers))
print(square)  

# Using filter
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  
Output:
[1, 4, 9, 16]
[2, 4]
5. Recursive Functions
  • A recursive function is a function that calls itself to solve smaller instances of a problem until a base condition is met.
  • For example – 
def factorial(n):
“””Calculate the factorial of a number using recursion.”””
if n == 0:
return1
return n * factorial(n – 1)

print(factorial(5))  # Output: 120
6. Nested Functions
  • Functions defined within other functions are called Nested or Inner Functions.
  • For example –
def outer_function():
    print(“This is the outer function.”)
    def inner_function():
        print(“This is the inner function.”)
    inner_function()
outer_function()
Output:
This is the outer function.
This is the inner function.
——————–  OR  ——————-
def outer_function():
    print(“This is the outer function.”)
    def inner_function():
        print(“This is the inner function.”)
    
outer_function()
Output:
This is the outer function.
7. Anonymous/Lambda Functions
  • A lambda function is a small anonymous function defined using the lambda keyword.
  • It can have multiple arguments but only one expression.
  • They are often used for short operations
  • For example – 
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(30, 50))  # Output: 80
square = lambda x: x ** 2
print(square(5))     # Output: 25
8. Generator Functions
  • Generator functions use the yield keyword toreturn values one at a time.
  • These functions are used for creating iterators.
  • For example –
def numbers():
for i in range(10):
        yield i

for num in numbers():
    print(num,end=” “)
Output:
0123456789
9. Coroutines Functions
  • Coroutines are special functions used for asynchronous/controlled programming.
  • They are defined with async def and can use the await keyword.
  • For example – 
import asyncio

async def msg():
    print(“Hello”)
    await asyncio.sleep(2)
    print(“World”)

asyncio.run(msg())
Output:
Hello
World
NB: Here, the output World appears after 2 seconds.
10. DocStrings Functions
  • This function is used to add a description as a comment inside the function in triple quotes to make it more understandable/readable.
  • The help(function_name) is used to view the docstring used in the function.
  • For example –
def multiply(a, b):
“””Program to Multiply two numbers and return the result.”””
return a * b
help(multiply)
Output:
multiply(a, b)
    Program to Multiply two numbers and return the result.

Advantages of Function in Python

  • Code Reusability and Avoid Redundancy : Functions allow one to write code once and reuse it multiple times. This reduces duplication, saves effort, and ensures consistency. By using functions, repetitive code can be avoided, resulting in cleaner and shorter code.
  • ModularityFunctions help in breaking a large program into smaller, manageable pieces (modules). Each function can handle a specific task, making the program easier to understand and maintain.
  • Simplified Debugging and Testing : Errors can be isolated to specific functions rather than debugging the entire program. Hence, we can test each function independently. With functions, unit testing becomes easier because individual functions can be tested in isolation from the rest of the code.
  • ScalabilityFunctions make programs easier to scale because additional features or functionality can be added by defining new functions without altering existing ones.
  • Improves Performance and MaintenanceFunction-based code is easier to optimize for performance and maintain over time. Changes to a function‘s logic need to be made only in one place, affecting all its usages.

      Disadvantages of Function in Python

      • Complexity in Small Programs : For very small scripts or programs, using functions can add unnecessary complexity. Sometimes, inline code is simpler and faster for straightforward tasks.
      • Overhead of Function Calls & Memory Consumption : Calling a function introduces a small overhead in terms of memory and execution time. This can impact performance, especially if a simple operation is repeatedly executed inside a function. Defining and calling functions requires additional memory for the function stack and variables. This can lead to inefficiency in memory-constrained environments.

      Loading

      Categories: Python Theory

      0 Comments

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      This site uses Akismet to reduce spam. Learn how your comment data is processed.