USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Functions

Lesson 10/15 | Study Time: 30 Min

1. Functions in Python


A function in Python is a reusable block of organized, structured, and meaningful code that performs a specific task. Instead of writing the same code again and again, we define a function once and call it whenever needed. Functions improve code reusability, reduce repetition, increase readability, and help in breaking large programs into smaller logical parts. Functions also allow you to process input values, perform operations, and return output values, making programs modular and easier to maintain. In Python, functions are treated as first-class objects which means they can be passed as arguments to other functions, returned as values, or stored in data structures like lists and dictionaries.


2. Why Functions Are Used? 


Functions are used in Python because they help make programs cleaner, easier to understand, and more efficient. A function is like a small machine inside a program: you give it some input, it performs a task, and it returns a result. Using functions improves the overall quality of the code in multiple ways, explained in detail below.


1. They reduce repetition of code 

When you write a piece of logic one time and use it again and again, you avoid repeating the same code. Without functions, you would have to copy-paste the same block of code every time you need it, which makes your program long and messy. Functions allow you to write that logic only once and call it whenever needed.
This not only saves time but also ensures that if you need to update that logic, you only have to change it in one place, not everywhere in the program.


2. They make debugging easier because code is divided into small parts

Debugging means finding and fixing errors in a program. When a program is written as one large block, it becomes difficult to locate where something went wrong.
Functions divide the entire program into smaller, manageable pieces.
If something breaks, you can directly check the function responsible for that task instead of going through the whole program. This makes troubleshooting faster and more organized.


3. They increase reusability — write once, use many times 

A function can be reused in the same program or even in different programs. Once a function is created, you do not have to rewrite that functionality again. You just “call” the function whenever you need it.
This saves effort and reduces the chance of making mistakes because the code inside the function has already been tested.
Reusability is especially useful when building large applications where the same operation is required at multiple places.


4. They improve clarity because code is well structured 

When a program is broken into functions, each function handles a specific task.
This gives the entire program a proper structure like chapters in a book.
Anyone reading the code can easily understand what each part does by simply looking at the function names and their purpose.
The main program becomes shorter and more readable because the actual logic is separated into functions.


5. They help in teamwork — different people can work on different functions 

In big projects, many programmers work together. Functions allow the project to be divided into independent parts, where every developer can work on a different function without interfering with others.
For example, one person can write functions for user input, another for data processing, and someone else for output formatting.
Later, all functions are combined to build the complete program.
This improves productivity and minimizes conflicts in team coding.


6. They allow modular programming 

Functions make the program modular, meaning the entire program is split into separate logical sections.
Each function is like a module that performs one task.
Modularity makes the software easier to update, maintain, expand, and understand.
Adding new features becomes simpler because you can write new functions without disturbing existing ones.


7. They support abstraction 

Abstraction means showing only what is necessary and hiding unnecessary details.
When you use a function, you do not need to know how it works internally.
You only need to know what it does and how to use it.
This reduces complexity because the function hides internal logic and exposes only the required interface.


8. They make the program scalable 

As your project grows, functions help you scale it smoothly.
You can keep adding new functionalities by writing new functions without rewriting or breaking old code.
This makes the project flexible and easier to expand in the future.



3. Function Declaration 


Function declaration means creating or defining a function in Python by using the def keyword. When you declare a function, you are telling Python that you are creating a reusable block of code that performs a particular task whenever it is called. A function declaration consists of several important components. The keyword def is the reserved word in Python that signals the start of a new function definition. The function_name is the identifier or label you give to that function so that you can call it later. The parameters represent the inputs that the function can receive, and they are completely optional depending on whether the function needs inputs or not. The colon : indicates the beginning of the function block, and everything written inside the function must be properly indented because indentation defines the function body in Python. The function body contains the statements that describe what the function actually does. A function may also use the return statement, which is optional, but when used, it returns a value from the function back to the caller.


Syntax of Function Declaration

def function_name(parameters):

    statement(s)


4. Calling a Function


Calling a function means you are instructing Python to execute the commands written inside the function. When a function is called, Python jumps to the function declaration, executes its internal statements, and then returns back to the point where it was called. A function call is performed by writing the function name followed by parentheses. If the function expects input values, those values are provided inside the parentheses and are known as arguments. The call triggers the function and makes the program run that specific block of code whenever required.


Syntax of Function Call

function_name(arguments)


5. Types of Functions in Python 


Python has mainly two types of functions. The first is built-in functions, which are functions already provided by Python’s core system, such as print(), len(), and type(). These functions are pre-written, ready to use, and help perform common tasks without writing code from scratch. The second type is user-defined functions, which are created by the programmer using the def keyword. These functions allow you to decide what the function should do, how it should work, and what inputs it should take. User-defined functions give full control over logic, structure, and customization.




6. Examples of Function Declaration 

Example 1: Simple Function Without Parameters

def greet():

    print("Hello, welcome to Python!")  # function body


greet()  # calling the function


In this example, the function greet() is declared using the def keyword and does not take any parameters. The function simply prints a welcome message when it is executed. The call to greet() causes Python to run the code inside the function body.


Example 2: Function With Parameters

def add(a, b):                   # a and b are parameters

    result = a + b               # adding the numbers

    print("Sum =", result)       # displaying result


add(10, 20)                      # calling with arguments


This function takes two parameters, a and b. When the function is called with the arguments 10 and 20, Python assigns those values to the parameters and performs the addition. The sum is then printed inside the function.


Example 3: Function With Return Statement

def multiply(x, y):

    return x * y   # returning the result to caller


output = multiply(5, 3)          # result stored in output

print(output)                    # prints 15


Here, the function multiply() performs multiplication but instead of printing the result, it returns it to the caller. The value is stored in the variable output, and printing it shows the result. The return statement allows values to be passed back from the function.


Example 4: Function With Default Parameters

def greet(name="User"):                 # default parameter

    print("Hello", name)


greet()                                 # uses default

greet("Mayank")                         # custom value


In this example, the parameter name has a default value of "User". If the caller does not provide a value, Python uses the default. But if a value is given, like "Mayank", that value replaces the default.


Example 5: Function With Multiple Return Values

def calculate(a, b):

    sum_val = a + b

    diff_val = a - b

    return sum_val, diff_val


x, y = calculate(10, 5)

print("Sum:", x)      # 15

print("Difference:", y)  # 5


Python allows a function to return multiple values at once. In this example, both the sum and difference are returned as a tuple, and the caller stores them in x and y.


7. Types of Arguments in Python Functions 

Python supports different ways of passing values to functions. Positional arguments are the values that must be passed in the same order as the function parameters. If the order is changed, the output will change because Python matches values by position. Keyword arguments provide values by specifying the parameter names explicitly, which means order does not matter because Python knows exactly which parameter is receiving which value. Default arguments are parameters that already have predefined values, and these values are used when the caller does not supply any argument. Variable-length arguments allow a function to accept any number of inputs. The *args form collects all extra positional arguments into a tuple, while **kwargs collects all extra keyword arguments into a dictionary. These flexible options make Python functions extremely powerful.


*Example of args

def total(*numbers):

    print(sum(numbers))


total(1, 2, 3, 4)



**Example of kwargs

def show(**details):

    print(details)


show(name="Mayank", age=21)


8. Anonymous (Lambda) Functions

A lambda function is a small, one-line function that does not have a name. It is used when a simple function is needed for a short time and defining a full function with def would be unnecessary. Lambda functions are mainly used in short calculations, filtering lists, sorting data, and functional programming contexts. They can take any number of arguments but only one expression, and the expression automatically becomes the return value.


Example

square = lambda x: x * x

print(square(6))    # 36


9. Docstring in Functions 

A docstring is a special string written inside a function to describe what the function does, how it works, what inputs it expects, and what output it returns. It acts like documentation for the function and helps other programmers quickly understand the purpose of the function without reading the entire code. A docstring is written as the first statement in the function body using triple quotes. It can be accessed using the __doc__ attribute, making it useful for documentation tools and editors.


Example

def add(a, b):

    """This function returns the sum of two numbers."""

    return a + b


print(add.__doc__)


10. Scope of Variables in Functions 


The scope of a variable defines where that variable can be accessed. A local variable is a variable that is declared inside a function and is only available within that function. Once the function finishes executing, the local variable is removed from memory. A global variable, on the other hand, is defined outside any function and can be accessed from anywhere in the entire program, including inside functions. If the same variable name is used both globally and locally, the local version takes priority inside the function. Understanding scope ensures that variables are properly managed and prevents unwanted changes.


Example

x = 10   # global variable


def test():

    y = 5    # local variable

    print(x, y)


test()

print(x)

Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.