Python - Functions

Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right now. 

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also, functions are a key way to define interfaces so programmers can share their code.

The most beautiful part of the function is that you can use the same code multiple times without rewriting it.

You can create a function by using the word def in Python.

def functionname():
    line 1 of function
    line 2 of function

Make user you follow indent rule while writing function. Let's see a basic function code.

def function1():
    print("This is my first function")

That's it, we have created our first function, but this function is not called yet. To use a function you need to call this function somewhere in your code. This function will not run without calling.

How to call a function?

Let see how we call a function:

Line 6, To call a function just type function name. That's all.

Passing arguments, variables to a function.

Functions may also receive arguments (variables passed from the caller to the function)

def function1(var1,var2):
    print(var1)
    print(var2)

A Function can return values

Functions may return a value to the caller, using the keyword 'return'. We can store the return value in some variable. For example:

def function1(var1,var2):
    return(var1 + var2)

value = function(a,b)

Exercise:

Now let's see below exercise to understand more about functions:

Output:

 

About the author

akarperiwal

0 Comments

Please login to comment