DEV Community 👩‍💻👨‍💻

Cover image for Easy understanding of functions in python
enosemi
enosemi

Posted on

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

Enter fullscreen mode Exit fullscreen mode

It is as simple as that, next is explaining the use of each keywords in the syntax.

  1. The def keyword is also know as define is the first keyword that a function should begin with.

  2. Parameters or arguments are placed within the parentheses and we use them inside our function body

  3. The 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

Enter fullscreen mode Exit fullscreen mode

The above code shows the function name sum that has two parameters for calculating the sum of two numbers

How to call a function

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)

Enter fullscreen mode Exit fullscreen mode

How To Define A Function(User-Defined Functions).

The four steps to defining a function in Python are the following:

  1. Use the keyword def to declare the function and follow this up with the function name.
  2. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon.
  3. Add statements that the functions should execute.
  4. 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:

  1. Built-in functions that were developed with the language e.g min()

  2. user-defined functions that are created by the users to solve their problem.

Top comments (1)

Collapse
 
henryagu profile image
HenryAgu

Nice one.

5 Websites To Learn Frontend Web Development Faster

In this article, Bentil Shadrack has curated 5 resourceful sites that will help you better you web development skills really fast.