- Built-in functions
- User-define Functions
A built-in function is functions that are pre-defined in Python like Math Function and String Function. User-defined functions are the function that is defined by the user.
Defining a Function in Python
- def function-name(arguments):
- ---------
- ---------
- ---------
- return Value;
Here,
def is the keyword in python which is used to define the function,
function-name is a user-defined function name, this name can be anything defined by the user,
arguments are a list of argument which you want to pass into the argument, and
return returns some value from the function.
Calling a Function
Above function can be called like the following:
- retunValue=function-name(arguments)
Example
-
-
-
-
- def MyFunction():
- print("Hello, C# Corner :)")
- return
-
-
- MyFunction()
Output
Passing parameters to function
-
-
- def Sum(a,b):
- return a+b
-
- result=Sum(5,6)
- print(result)
Output
Returning Multiple Values from the function
In Python, we can return multiple values also. To return multiple values we use comma(,) when we return value.
Example
-
- def ReturnMultipleValues():
- a=8
- b=9
- c=10
- return a,b,c
-
- i,j,k=ReturnMultipleValues();
- print(i)
- print(j)
- print(k)
Output
Calling Function With Argument
We can call a function in Python by the following different ways:
- Required Arguments
- Keyword Arguments
- Default Arguments
- Variable-Length Argument
Required Argument
When arguments are passed into the function in the exact order as the function is defined.
Example
- def MyFunction(arg):
- print(arg)
- return
- MyFunction("Hello C# Corner :)")
Keyword Argument
When function is called by its parameter name.
- def MyFunction(arg1,arg2):
- print(arg1)
- print(arg2)
- return
-
- MyFunction(arg2="Somani",arg1="Sourabh")
Output
Default Argument
Sometimes we can define a function in Python with default argument value, so when the function will be called and if we do not pass the argument, then by default it will take default values.
- def MyFunction(a=0,b=0):
- print(a+b)
- return
-
- MyFunction()
- MyFunction(a=5)
- MyFunction(b=6)
- MyFunction(a=10,b=20)
Output
Variable-Length Arguments
Sometimes we don't know the number of arguments which we will pass into the function. So we can define a function with a variable-length argument, So the number of arguments may vary according to need.
An asterisk(*) sign is placed before the variable name so the argument list may vary according to need.
Example: We want to add
n numbers which we will pass to the function.
- def Add(*args):
- sum=0
- for i in args:
- sum+=i
- return sum
- print(Add(5,6,7,8,9,10))
- print(Add(1,2,3,4,5,6,7,8,9,10))
Thanks!