Python Basics #10 – Python Functions

In this last and the 10th part of the Python Basics tutorial, we will learn about python functions and how to use them.

What is a python function?

The function is a set of statements (or a block of code) which is executed only when the function is called.

Every function has a function name. A function is called using the help of a function name. We can even pass “arguments” (inputs) in a function called “parameters”.

def FunctionName(arg1, arg2, …..):
blockOfCode

This is how we define a function.

Let’s learn python functions with the help of some examples.

Example 1 – Simple “hello world” function

Defining the function

We will name the function as HelloWorld. As this is a simple function printing just one line, we will not be passing any parameters.

>>> def HelloWorld():
...     print("Hello World!!!")
...
>>> 

Calling the function

To call the function, we just write the function name with the parenthesis “()” as shown below.

>>> HelloWorld()
Hello World!!!
>>>

Example 2 – Check if a number is odd or even

Example 2 – Check if a number is odd or even

We will name this function as “CheckOddEven”.

Now, to be able to check if a number is odd or even, we would need a number as input to the function. Hence, here we will have a number of arguments (also called parameters).


Parameters are always fed to the function by specifying the variable in the function’s parenthesis. (Note: we can pass any number of parameters to a function.

Defining the function

>>> def CheckOddEven(a):
...     if (a%2 == 0):
...             print("Given number is even.")
...     else:
...             print("Given number is odd.")
...
>>>

Calling the function

>>> CheckOddEven(4)
Given number is even.
>>>
>>> CheckOddEven(9)
Given number is odd.
>>>

Example 3 – Sum a numbers in a list

We will name this function as “ListSum”. Here the parameter will be a list.

Defining the function

>>> def ListSum(lst):
...     sum = 0
...     for i in lst:
...             sum += i
...     return sum
...
>>>

Calling the function

>>> inputList = [1,2,3,4,5,6,7]
>>>
>>> ListSum(inputList)
28
>>> ListSum([10,20,30,40])
100
>>>

As this function has a return value, we can even store the functions result in a variable.

>>> a = ListSum([1,1,1,1,1])
>>> a
5
>>>

Most of the time, it will be helpful to store the result of a function in a variable rather than printing it.
Doing this will help us use the value later if required.

With this, we come to an end to this python basics tutorial. Hope things were quite clear and you have a better idea of the language now.

Back : Python Basics #9 – Collections

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: