Notes
Categories

Functions in Python [ English ]

< Prev Next >

1. Introduction

A function is a fundamental building block in programming that allows a set of instructions to be grouped together and executed whenever required. Instead of writing the same code repeatedly, a function enables code reuse, modularity, and better organization.

In Python, functions are widely used to structure programs in a clear and efficient manner.


2. Definition

A function is a named block of code that performs a specific task and can be executed (called) whenever needed.


3. Syntax of a Function

def function_name(parameters):
    # block of code
    return value

4. Example of a Function

def greet():
    print("Hello, Welcome to Python!")

Function Call:

greet()

Output:

Hello, Welcome to Python!

5. Functions with Parameters

Functions can accept input values called parameters.

def add(a, b):
    result = a + b
    print(result)

Call:

add(5, 3)

Output:

8

6. Functions with Return Values

Functions can return a value using the return statement.

def square(x):
    return x * x

Call:

result = square(4)
print(result)

Output:

16

7. Types of Functions in Python

7.1 Built-in Functions

These are predefined functions provided by Python.

Examples:


7.2 User-defined Functions

Functions created by the programmer using the def keyword.


7.3 Lambda Functions (Anonymous Functions)

These are small, one-line functions defined using the lambda keyword.

square = lambda x: x * x
print(square(5))

8. Advantages of Using Functions


9. Key Concepts


10. Key Insight

Functions are essential for writing efficient and scalable programs. They promote structured programming and make code easier to understand, reuse, and maintain.


11. Conclusion

Functions in Python provide a powerful way to organize code into reusable components. By mastering functions, programmers can write cleaner, more efficient, and more maintainable programs.

< Prev Next >