Python Functions
Python Functions
Functions
Function
In Python, Function is a block of reusable code that performs a specific task. Functions
provide modularity and help in organizing code into manageable chunks. In Python,
functions are defined using the def keyword followed by the function name and parentheses
containing any parameters.
In General, Function is set of instructions which will be used to do specific task again and
again.
Syntax:
def function_name(parameter1, parameter2, ...):
# Function body
# Statements to perform a task
return result
Parts of a Function:
Python function arguments refer to the values passed to the function when it is called.
There are different types of arguments that can be used in Python functions. Here are the
main types:
Positional Arguments
Keyword Arguments
Default Arguments
Variable-Length Arguments
Arbitrary Keyword Arguments (**kwargs):
Arbitrary Positional Arguments (*args)
Positional Arguments:
Positional Arguments:
Positional arguments are passed to a function based on their position in the
function call.
The order and number of arguments in the function call must match the order
and number of parameters in the function definition.
def calc(a, b):
print("a value is ", a)
print("b value is ", b)
return a+b
Keyword Arguments:
• Keyword arguments are passed to a function with their corresponding parameter
names.
• They allow you to specify arguments in any order, as long as you provide the
parameter names.
def calc(a, b):
print("a value is ", a)
print("b value is ", b)
return a+b
Default Arguments:
• Default arguments have default values specified in the function definition.
• If a value is not provided for a default argument during the function call, the default
value is used.
def calc(a, b,c=0):
print("a value is ", a)
print("b value is ", b)
print(”c value is ", c)
return a+b+c
Variable-Length Arguments:
• Variable-length arguments allow a function to accept a
variable number of arguments.
• They are specified using *args for positional arguments and
**kwargs for keyword arguments.
def calc(*args):
sum=0
for I in args:
sum=sum+i
Return sum