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.
A function is a named block of code that performs a specific task and can be executed (called) whenever needed.
def function_name(parameters):
# block of code
return value
def → keyword used to define a functionfunction_name → name of the functionparameters → inputs to the function (optional)return → sends output back (optional)def greet():
print("Hello, Welcome to Python!")
Function Call:
greet()
Output:
Hello, Welcome to Python!
Functions can accept input values called parameters.
def add(a, b):
result = a + b
print(result)
Call:
add(5, 3)
Output:
8
Functions can return a value using the return statement.
def square(x):
return x * x
Call:
result = square(4)
print(result)
Output:
16
These are predefined functions provided by Python.
Examples:
print()len()type()range()Functions created by the programmer using the def keyword.
These are small, one-line functions defined using the lambda keyword.
square = lambda x: x * x
print(square(5))
Functions are essential for writing efficient and scalable programs. They promote structured programming and make code easier to understand, reuse, and maintain.
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.