top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Functions in Python

Introduction

In this tutorial, we plunge deep into the world of Python functions. From understanding their core essence to grasping their utility in Python, this comprehensive guide serves as an essential toolkit for Python enthusiasts wanting to elevate their skill set.

Overview

Functions in Python act as the fundamental building blocks of the language. Integral to fostering efficient and clean coding, they provide a mechanism to segment operations into modular tasks. These tasks, encapsulated within functions, ensure code is not just functional but also readable. In this comprehensive tutorial, we’ll cover all these and more.

What are Functions in Python?

Python functions are one of the foundational building blocks of the language. They can be visualized as self-contained modules that perform a specific task. These modules encapsulate a set of actions, allowing a more organized, modular, and readable code. Functions intake data (often referred to as arguments or parameters), work upon it, and then produce an output.

Core Components:

  • Function Name: It acts as an identifier. This is the label by which the function is later referenced or invoked in the program. Naming functions appropriately, in line with their functionality, aids in enhancing code readability.

  • Parameters: These are the inputs a function accepts. They are enclosed within parentheses immediately following the function name. Parameters are optional; a function can be defined without them.

  • Function Body: This is the heart of the function. Comprising a series of Python statements, it defines the specific actions the function will undertake. The function body is executed every time the function is called.

  • Return Statement: While not mandatory, the return statement sends a result back to the caller. It signifies the end of the execution of a function.

Function Declaration in Python

In Python, you can declare functions using the def keyword. A function is a block of organized, reusable code that performs a specific task. Here's the general syntax for declaring a function in Python:

def function_name(parameters):
    """
    Function docstring (optional)
    """
    # Function body
    # Perform tasks here
    return result  # Optional return statement

Let's break down each part of the function declaration:

  • def: This keyword is used to declare a function.

  • function_name: Replace this with the name you want to give to your function. Function names should be descriptive and follow Python's naming conventions (lowercase with underscores for readability).

  • parameters: These are the input values that the function takes. You can have zero or more parameters. Parameters are enclosed in parentheses and separated by commas.

  • Function docstring: This is an optional multi-line string that provides a brief description of the function's purpose, parameters, and return value. It's good practice to include docstrings to explain how to use the function.

  • Function body: This is where you define the tasks the function should perform. It consists of one or more statements.

  • return: This is an optional statement that specifies the value the function should return. If the function doesn't have a return statement, it returns None by default.

Example:

Code:

def greet(name):
    """
    Greets the person with the given name.
    """
    return f"Hello, {name}!"
    
message = greet("Alice")
print(message)  # Output: Hello, Alice!

The Various Types of Functions in Python  

In Python, functions can be categorized into several types based on their purpose and behavior. Here are the main types of functions:

  • Built-in Functions:

These are functions that are pre-defined in Python and are available for use without requiring any additional imports. Examples include len(), print(), type(), range(), and sum().

  • User-Defined Functions:

These are functions created by users to perform specific tasks. They are defined using the def keyword. User-defined functions promote code reusability and modularity.

  • Anonymous Functions (Lambda Functions):

Lambda functions are small, unnamed functions defined using the lambda keyword. They are often used for short, simple operations that can be expressed in a single line of code.

  • Recursive Functions:

Recursive functions are functions that call themselves as part of their execution. They are particularly useful for solving problems that can be divided into smaller instances of the same problem.

  • Higher-Order Functions:

Higher-order functions take one or more functions as arguments and/or return a function as their result. They enable functional programming paradigms and can make code more concise and readable.

  • Pure Functions:

Pure functions are functions that always produce the same output for the same input and have no side effects. They don't modify external variables or objects, which makes them easier to reason about and test.

  • Impure Functions:

Impure functions have side effects, such as modifying external state or variables. They can lead to unexpected behavior and make code harder to understand and test.

  • Generator Functions:

Generator functions use the yield keyword to yield values one at a time, allowing for memory-efficient iteration over large datasets. They are used to create iterators using the concept of lazy evaluation.

  • Decorator Functions:

Decorators are functions that modify the behavior of other functions. They allow you to add functionality to a function without modifying its code directly. Decorators are often used for tasks like logging, authentication, and memoization.

  • Static Methods:

Static methods are defined inside a class but are not bound to the instance. They can be called on the class itself and are often used for utility functions that don't require access to instance-specific data.

  • Class Methods:

Class methods are defined inside a class and are bound to the class rather than an instance. They can access and modify class-level attributes and are often used for factory methods or alternate constructors.

These are some of the main types of functions in Python, each serving a specific purpose and contributing to different programming paradigms and best practices.

Creating a Function in Python

Code:

# function creation
def fun():
print("Welcome to upGrad!")

# call a function
fun()

Calling Python Functions  

Code:

# function creation
def fun():
print("Welcome to upGrad!")

# call a function
fun()

Python Function with Parameters

Code:

def greet(name):
    return f"Hello, {name}!"

person = "Alice"
message = greet(person)
print(message)  # Output: Hello, Alice!

Python Function Arguments  

Code:

def add_numbers(x, y):
    return x + y

result = add_numbers(5, 3)
print(result)  # Output: 8

The Different Types of Python Function Arguments 

Default argument

Code:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

message1 = greet("Alice")
message2 = greet("Bob", "Hi")

print(message1)  # Output: Hello, Alice!
print(message2)  # Output: Hi, Bob!

Keyword arguments (named arguments)

Code:

def display_info(name, age, city):
    return f"Name: {name}, Age: {age}, City: {city}"

info = display_info(name="Alice", city="New York", age=30)
print(info)  # Output: Name: Alice, Age: 30, City: New York

Positional arguments

Code:

def add_numbers(x, y):
    return x + y

result = add_numbers(5, 3)
print(result)  # Output: 8

Arbitrary arguments

Code:

def display_names(*names):
    for name in names:
        print(name)

display_names("Alice", "Bob", "Charlie")

Pass by Reference vs. Pass by Value  

Code:

def myFun(p):
p[0] = 300
last = [100, 110, 120, 130, 140, 150]
myFun(last)
print(last)

Docstring

Code:

def evenOdd(p):
"""Function to check whether the number is even or odd"""

if (p % 2 == 0):
print("even")
else:
print("odd")
print(evenOdd.__doc__)

Python Function within Functions  

Code:

def outer_function(x):
    def inner_function(y):
        return y ** 2
    
    result = inner_function(x)
    return result

input_number = 3
output = outer_function(input_number)
print("Result:", output)  # Output: Result: 9

Anonymous Functions in Python  

Code:

numbers = [1, 2, 3, 4, 5]

# Using lambda in sorting
sorted_numbers = sorted(numbers, key=lambda x: x % 2)  # Sort by odd/even

# Using lambda in mapping
squared_numbers = list(map(lambda x: x ** 2, numbers))

# Using lambda in filtering
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(sorted_numbers)    # Output: [2, 4, 1, 3, 5]
print(squared_numbers)   # Output: [1, 4, 9, 16, 25]
print(even_numbers)      # Output: [2, 4]

Return Statement in Python Function  

Code:

def add_numbers(x, y):
    result = x + y
    return result

sum_result = add_numbers(3, 5)
print("Sum:", sum_result)  # Output: Sum: 8

Advantages of Python Functions

1. Modularity:

Python functions advocate a modular design. Modularity implies that a complex system, in this case, a program, is divided into separate modules or functions. Each function deals with a specific sub-task, allowing for greater clarity.

This design not only makes it easier for developers to understand and navigate through the codebase but also encourages collaborative work. Different developers can work on different functions simultaneously, without intruding on each other's code.

2. Breakdown Complexity:

Functions are excellent tools to disintegrate a complex operation into more digestible sub-tasks. By compartmentalizing code into functions, it becomes simpler to track, debug, and understand the logic.

Each function stands alone, ensuring that the flow of data and logic is continuous and transparent within that segment. This reduces cognitive overload, making troubleshooting and optimization efforts more focused.

3. Reusability:

One of the most celebrated features of functions is reusability. A function is like a pre-packaged unit of code ready to perform its defined task whenever called upon.

This means you can craft a well-optimized function once and then deploy it across various parts of your application, or even across different projects.

This upholds the DRY (Don't Repeat Yourself) principle of coding, ensuring efficiency and consistency.

4. Maintainability:

A direct offspring of modularity and reusability is the maintainability of the code. When code is structured into specific functions, updating a feature or fixing an issue becomes much more straightforward.

Developers can zero in on the exact function that needs alteration, making changes without disturbing the larger machinery of the software. This modular approach reduces the risk of introducing new bugs when making updates.

5. Flexibility:

Functions in Python, especially when they're parameterized, offer a high degree of flexibility. Parameterized functions accept input values when they're called, allowing developers to mold a generic solution to suit diverse scenarios.

This means that a single function can handle a wide range of situations, reducing the need for creating multiple, similar functions.

6. Namespace Isolation:

Python functions provide a sanctuary for local variables. When a variable is defined within a function, it remains local to that function, invisible to the outside world.

This ensures there's no unintended interference between the internal variables of the function and external variables, offering a robust mechanism to prevent accidental data overlaps and manipulations.

The Scope and Lifetime of Variables

Code:

global_variable = "I am global"

def my_function():
    local_variable = "I am local"
    print(global_variable)
    print(local_variable)

my_function()

print(global_variable)
# print(local_variable)  # This would raise an error because local_variable is not accessible here.

Python Capability inside Another Capability

Code:

def outer_function(x):
    def inner_function(y):
        return x + y
    
    return inner_function

add_five = outer_function(5)
result = add_five(3)  # This is equivalent to calling inner_function(3)
print(result)  # Output: 8

Conclusion

In summary, Python functions, with their diverse types and components, are indispensable tools for programmers. Whether it's the built-in convenience of predefined functions or the flexibility offered by user-defined and lambda functions, they play a pivotal role in crafting efficient, organized, and readable code. The ability to use recursion and generators adds more depth, accommodating specific computational needs. Ultimately, a firm grasp of functions enables streamlined, modular programming, ensuring Python's continued popularity and relevance in diverse applications. 

At upGrad, we offer industry-relevant upskilling courses to help you kick-start your journey as a Python developer. 

FAQs

  1. How to call a function in Python with arguments?

In Python, when you want to call a function with arguments, you simply pass the required values within the parentheses right after the function's name. These values then get mapped to the function's parameters in the order they are defined. For example, if you have a function def greet(name, age):, you can call it with greet("Alice", 30). 

  1. What does DEF in Python signify?

In Python, "DEF" doesn't stand for an abbreviation or acronym. Instead, it's short for "define". The def keyword is used to declare or define a user-defined function. By using def, you signal to Python that you're about to specify a new function, followed by its name, parameters, and the body of code that constitutes the function's operations.

  1. How does the Python function return operate?

The return statement in Python functions is used to send a result back from the function to where it was called. Once the return statement is executed, the function's execution is halted, and control is passed back to the caller. The value or expression specified after the return keyword is what's sent back. If no value or expression is provided, the function will return None by default.

  1. Is there a list of all functions available in Python?

Absolutely! Python's official documentation is a rich resource that provides an exhaustive list of built-in functions. Each function is accompanied by a brief description, syntax, and examples, making it easy for developers to understand its purpose and usage. 

Leave a Reply

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