Function is a block of code which when called , perform the task and return something. All Python function return something and if not they return none.
Benefits of Using Functions
- Increase Code Readability
- Increase Code Reusability
Syntax for Function Declaration:
def function_name (parameters):
#statement
return expression
function_name(arguments )
Here in the above we are defining the function with the keyword def , following it is the function_name with which we have defined the function. Inside the paranthesis is the parameters which we are sending to this function then this function will work on this given set of parameters as defined in the body of function statements and then return the result to us.
To call this function i.e when to execute it we called it below with the name of function following the arguments we passed. The arguments we passed at the time of call are basically copied into the parameters list.
so Parameters: refers to variable defined in function definition.
Argument: refer to actual value used when function is called. Arguments are often shortened to args in Python documentations.
Example:
def my_function():
print("Hello from a function")
my_function()
Output
Hello from a function
Types of Function Arguments :
Python supports various types of arguments that can be passed at the time of the function call. In Python, we have the following function argument types in Python:
- Default argument
- Keyword arguments (named arguments)
- Positional arguments
- Arbitrary arguments (variable-length arguments *args and **kwargs)
Note: By default, a function must be called with the correct number of arguments i.e if your function expects 3 arguments, you have to call the function with 3 arguments, not more, and not less.
Default argument: A default argument is one that assumes a default value if a value is not provided in the function call for that argument. Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
Output:
I am from Sweden
Positional Argument: We used the Position argument during the function call so that the first argument (or value) is assigned to first position and the second argument (or value) is assigned to second. By changing the position, or if you forget the order of the positions, the values can be used in the wrong places.
Example:
def nameClass(name, standard):
print("Hi, I am", name)
print("I study in standard", class)
print("Case-1:")
nameClass("Suraj", 7)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameClass(7, "Suraj")
Output:
Case-1:
Hi, I am Suraj
I study in standard 7
Case-2:
Hi, I am 7
I study in standard Suraj
Keyword Arguments : We can also send arguments with key=value syntax. In this the order of arguments won’t matter.
Example:
def child_name(child3, child2, child1):
print("The youngest child is " + child3)
child_name(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Output:
The youngest child is Linus
Arbitrary Arguments: In Python Arbitrary Keyword Arguments 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)
Arbitrary Arguments -*args: When we do not know how many arguments will be passed into our function, add a *
before the parameter name in the function definition. It basically acts like a tuple which will be unpacked later in definition i.e the function will receive a tuple of arguments, and can access the items accordingly
Example:
# *args for variable number of arguments
def myFun(*arguments):
for arg in arguments: #unpack
print(arg, end=' ')
myFun('Hello', 'Welcome', 'to', 'My world')
Output:
Hello Welcome to My world
Arbitrary Arguments -*kwargs : If the number of keyword arguments is unknown, add a double **
before the parameter name. Here the function will receive a dictionary of arguments, and can access the items accordingly.
Example:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Ram", lname = "Prakash")
Output:
His last name is Prakash
Types of Function:
- Built-in library function: These are standard functions in Python that are available to use.
- User-defined function: We can create our own functions based on our requirements.
Return Statement:
If we wanted a function to return a value use return statement following the value of calculated value we want to return. The function return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller
Example:
def cube_value(num):
"""This function returns the square
value of the entered number"""
return num**3
print(cube_value(2))
Output:
8
Note: The return statement can consist of a variable, an expression, or a constant which is returned at the end of the function execution. If none of the above is present with the return statement a None object is returned.