Description: A function in Python is a block of reusable code that performs a specific task. Functions allow you to group statements together and execute them when needed, which helps avoid code repetition, makes the code more modular, and improves readability.Functions can take inputs, perform operations, and return a result.
Step-by-Step Process
Define a function: Python use 'def' keyword followed by the function name and a pair of parentheses () which can include parameters.Ex: def function_name(parameter):
Calling the function: After defining a function, you can "call" it by using the function name followed by parentheses.If the function has parameters, you provide the required arguments inside the parentheses.Ex: function_name(arguments)
Function parameter and arguments: Functions in Python can accept parameters or arguments, which are values passed to the function when it is called.Ex: def function_name(parameter1, parameter2="default_value"):
Return Statement: A function can return a value using the return statement.If function executes a return statement, it ends the function's execution and sends a result back to the caller.
Function scope: Local scope: Calls and Accessed only inside the function. Global scope: calls outside if the function and accessed from anywhere.
Variable-Length Arguments: Arbitrary Positional Arguments (*args): Collects extra positional arguments into a tuple. Arbitrary Keyword Arguments (**kwargs): Collects extra keyword arguments into a dictionary.
Sample Code
def mul_numbers(a, b):
result = a * b
return result
num1=mul_numbers(5, 5)
print("Output for a function:")
print("Result is :", num1)
print()
#Global scope
print("Output for local and global scope:")
x = 10
def my_function():
#Local scope
y = 5
print("Inside function:")
print("x (global) =", x)
print("y (local) =", y)
my_function()
print("Outside function:")
print("x (global) =", x)