It is a block of statements that are used to perform a specific task. we do create a function when we need to use the same code multiple times, in this case, we create a function and call it multiple times.
Advantages of using functions in Python:
Code Reusability and Code Readability
There are two types of functions:
- User Defined Function
- Pre-Built Function
Python Function Declaration
keyword function name (parameter):
statements
return expression
Python Function without parameter.
def animal():
print('human is a social animal')
animal()
Arguments and Parameter in function:
Parameter: It is the variable defined within the parenthesis during the function definition.
An argument is a value that is passed function when it is called.
def add(a,b):
return a+b
add(1,2)
Types of Argument in Python:
Default Argument
Keyword Arguments
Positional Arguments
Arbitrary Arguments
Default Argument: A default argument is a parameter that assumes a default value if the value is not provided in a function call for that argument.
def fun(x=60):
print(x)
fun()
Keyword Argument: Keyword arguments are linked to the argument of linked functions. The idea is to allow the caller to specify the argument name with values so that the caller doesn't need to remember the order of parameters.
def fun(y,x):
print(x+y)
fun(x=60,y=90)
Positional Arguments: Required arguments are those supplied to a function during its call in a predetermined positional sequence. The number of arguments required in the method call must be the same as those provided in the function's definition.
def fun(y,x):
print(x+y,x,y)
fun(60,90)
Arbitrary Arguments: In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments to a function using special symbols. There are two special symbols:
- *args in Python (Non-Keyword Arguments)
- **kwargs in Python (Keyword Arguments)
*kwargs
def fun(**kwargs):
print(kwargs.items())
for k,v in kwargs.items():
print(k,v)
fun(a=60,b=90,c=89,d=100)
c=lambda x:x*x
c(8)
def c(x):return x*x
c(8)