In Python, a Function is a reusable block of code that performs a specific task. Functions help in breaking down large programs into smaller, manageable, and organized chunks. This concept is known as modularity, and it is one of the most important principles in software development.
Reusability: Write code once and use it many times without rewriting it.
Abstraction: You only need to know what a function does, not necessarily how it does it.
Maintainability: If a bug occurs, you only need to fix it in one place.
Readability: Well-named functions make your code look like a story rather than a wall of logic.
The def Keyword: Used to start the function definition.
Function Name: A unique identifier following the same naming rules as variables (snake_case).
Parameters (Optional): Input values passed inside the parentheses ().
The Colon (:): Marks the end of the function header.
Docstring (Optional): A string literal used to document what the function does.
Function Body: The indented block of code that performs the task.
Return Statement (Optional): Sends a result back to the caller.
def function_name(parameters): """Docstring: Explains what the function does.""" # Logic goes here return result
A basic function that simply prints a message.
def greet_user(): """Display a simple greeting.""" print("Welcome to the Functions module!") # Calling the function greet_user()
Parameters act as placeholders for the data you pass into the function.
def personalize_greeting(username): """Greeting with a specific name.""" print(f"Hello, {username}! Ready to learn?") # 'Admin' is the argument passed to the parameter 'username' personalize_greeting("Admin")
The return statement allows a function to send a value back to the main program. Once a return is executed, the function exits immediately.
def calculate_square(number): """Return the square of a number.""" return number ** 2 # Saving the returned value into a variable result = calculate_square(5) print(f"The square of 5 is: {result}")
Definition vs. Calling: Defining a function does not execute it. You must "call" the function by its name followed by () to run the code.
Indentation: All code within the function must be indented.
NoneType: If a function doesn't have a return statement, it implicitly returns None.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION