FunctionInPython
FunctionInPython
What is Function?
In Python, the function is a block of code defined with a name.
We use functions whenever we need to perform the same task multiple
times without writing the same code again.
It can take arguments and returns the value.
Function improves efficiency and reduces errors because of the reusability
of a code.
Once we create a function, we can call it anywhere and anytime.
The benefit of using a function is reusability and modularity.
1. Built-in function
2. User-defined function
Built-in function
The functions which are come along with Python itself are called a built-in
function or predefined function.
Some of them are listed below.
range(), id(), type(), input(), eval() etc.
User-defined function
Creating a Function
Use the def keyword with the function name to define a function.
Next, pass the number of parameters as per your requirement. (Optional).
Next, define the function body with a block of code. This block of code is
nothing but the action you wanted to perform.
In Python, no need to specify curly braces for the function body. The
only indentation is essential to separate code blocks. Otherwise, you will get an
error.
Here,
function_name:
Function name is the name of the function. We can give any
name to function.
parameter:
Parameter is the value passed to the function. We can pass any
number of parameters. Function body uses the parameter’s value to
perform an action
function_body:The function body is a block of code that performs some task.
This block of code is nothing but the action you wanted to accomplish.
return value: Return value is the output of the function.
Note: While defining a function, we use two keywords, def (mandatory) and
return (optional).
Now, Let’s the example of creating a simple function that prints a welcome
message.
# function
def message():
print("Welcome to Python")
Output
Welcome to Python
Let’s create a function that takes two parameters and displays their values.
In this example, we are creating function with two parameters ‘ name’ and ‘age’.
# function
def course_func(name, course_name):
print("Hello", name, "Welcome to MMN")
print("Your course name is", course_name)
# call function
course_func('DSK', 'Python')
Output
Calling a function
Once we defined a function or finalized structure, we can call that function
by using its name.
To call a function, use the name of the function with the parenthesis, and if
the function accepts parameters, then pass those parameters in the parenthesis.
Example
def even_odd(n):
# check number is even or odd
if n % 2 == 0:
print('Even number')
else:
print('Odd Number')