Python Functions
Python Functions is a core Python concept covering python Functions: --8<-- "core-logic/functions.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Functions: Reusable Code Blocks
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
Why use Functions?
- Reusability: Define code once, and use it many times.
- Organization: Break down large programs into smaller, manageable pieces.
- Abstraction: You don't need to know how the function works, just what it does (like a remote control).
Components of a Function
- Definition: Creating the function.
- Arguments/Parameters: The information you send into the function.
- Body: The code that performs the task.
- Return Value: The result the function sends back.
Think of a function like a recipe. The recipe is the definition; the ingredients are the parameters; the cooking is the body; and the finished dish is the return value.
Creating a Function
In Python, a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
my_function()
Arguments (Parameters)
Information can be passed into functions as arguments.
def greet(name):
print(f"Hello, {name}!")
greet("Vishnu")
greet("Student")
Return Values
To let a function return a value, use the return statement:
def multiply(x):
return 5 * x
result = multiply(3)
print(result) # 15
The *args and **kwargs
*args: If you do not know how many arguments will be passed into your function.**kwargs: If you do not know how many keyword arguments will be passed.
Variables created inside a function are local and cannot be used outside. Variables created outside are global.