17
Easy understanding of functions in python
We should all understand a function is a block of organized reusable code for performing single or related action. Python has many built-in functions that we have probably used e.g print()
,input()
, etc. But there are also user-defined functions which allows you to create a block of code to perform your bidding at any time it is called.
Now let's look at the python function syntax:
def functionname(parameters):
'''block of code'''
pass
It is as simple as that, next is explaining the use of each keywords in the syntax.
The
def
keyword is also know as define is the first keyword that a function should begin with.Parameters
orarguments
are placed within the parentheses and we use them inside our function bodyThe code block begins after a colon and is usually indented
Let's put this into practice and write a function that takes the sum of two numbers.
def sum(num1, num2):
'''this function adds two numbers'''
Return num1 + num2
The above code shows the function name sum
that has two parameters for calculating the sum of two numbers
In the previous code we wrote our function wasn't called so if we execute the command it will return nothing. To call a function we just type the function name and the desired parameters.
Let's try another example.
Def sum(a , b):
#this function add two numbers
Return num1 + num2
#now call the function
sum(2,5)
The four steps to defining a function in Python are the following:
- Use the keyword def to declare the function and follow this up with the function name.
- Add parameters to the function: they should be within the parentheses of the function. End your line with a colon.
- Add statements that the functions should execute.
- End your function with a return statement if the function should output something. Without the return statement, your function will return an object None.
Finally I want us to know we have two types of functions in python which are:
Built-in functions that were developed with the language e.g min()
user-defined functions that are created by the users to solve their problem.
17