Quick Reach
The function in Python
As in other programming languages, Python provides a way to create and use the functions in its programs.
A python function is a block of code that may take one or more input parameters, executes and may return a value. Functions can be used in Python programs repeatedly. A function’s code will only be executed once this is called.
There are plenty of built-in functions, however, programmers can create their own. Functions make the life of programmers quite easier in that you don’t have to write the code again and again for the same purpose.
You even don’t need to go through the code, if a function is written by some other programmer, like Python built-in functions.
Writing your own functions in Python
There are two parts of python function:
- Defining a function
- Calling a function
Syntax of creating or defining a function
def function_name ( params ):
“function’s purpose statements or instructions etc.”
# Statements to be executed
return [expression]
So what above lines are doing?
- A function is defined by using the def keyword.
- The def is followed by function name and parenthesis.
- Any input parameters are given within the parenthesis, followed by ‘:’
- The first line of Python function can be documentation containing the purpose or instruction of the function (optional).
- After that, statements to be executed with indentation.
- The return statement may contain parameter, sending back to the caller of the function. If no argument is given in return statement, it will be taken as return nothing.
Defining a function example
The example below defines a simple function, that takes two parameters as input, sums up and print the sum of two. As such, the function is only defined and not called, if you run this code it will display nothing.
1
2
3
4
5
|
def func_sum(a, b):
c = a + b
print (c)
|
Calling a function example
Now we will call the above function, where we will send two parameters. The complete code of creating and calling the function is:
1
2
3
4
5
6
7
8
9
|
def func_sum(a, b):
c = a + b
print (c)
#Calling function here
func_sum(10,15)
|
The output will be:
25
Using Python return statement example
A function in the following example simply takes two parameters (numbers), sum those up and returns one expression.
1
2
3
4
5
6
7
8
9
|
def func_sum(a, b):
c = a + b
return (c)
z = func_sum(10,15)
print (z)
|
The output will be:
25
Also see Class in Python
Leave A Comment?