PYTHON
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:
1.Function Name: It is the identifier for the function. It should be descriptive
and follow Python naming conventions.
2.Parameters (or Arguments): These are values passed into the function.
They are placeholders for the actual values that the function will operate on.
Functions can have zero or more parameters.
3.Function Body: It consists of statements that define what the function does.
It's the block of code that gets executed when the function is called.
4.Return Statement: It is optional. It specifies the value that the function
should return to the caller. If there's no return statement or it doesn't specify a
value, the function returns None.
Function arguments
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
Function call : calc(10,20)
calc(40,60)
Keyword Arguments:
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
Function call : calc(a=10,b=20)
calc(b=50, a=60)
Default Arguments
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
Function call : calc(a=10,b=20)
calc(b=50, a=60,c=40)
Variable-Length Arguments:
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