Python | Functions | User Defined Functions

As in any other programming languages, in Python you can define your own function. The syntax is as follows:

def name_of_function(parameters):
	Process data or variables
	Return [Some Expression or Variable]

The def keyword is used in Python to define a function. It is followed by the name of the function which can be whatever the programmer wants but not Python reserved words.

After you give your function a name you can put in (it is optional) parameters within parenthesis. You can put as many parameters as you want but you have to separate them with a comma.

Whitespace is used to denote a function block after the colon :. Everything typed below the colon that is indented with white space, is part of the function.

Let’s create a simple function.

def simple_func():
	print('This is a function')
	x = 2 + 5
	print(x)
simple_func()

Python functions

We use def keyword to declare the function that we named simple_func(). First we tell the function to print on the screen the message “ This is a function”. Next we declare the variable x which has a value of “2 + 5”.

The last thing we wanted the function to do is to print on the screen the value of x, which is 7.

The last line is the call of the function. The function won’t do anything until you call it.

This function doesn’t take any parameters in. The parameters are data or variables that you pass along to a function to work with, to do operations with them.

Let’s take a look at the following example:

def addition_func(no1,no2):
	rezult = no1 + no2
	print(rezult)
addition_func(5,7)

When we call the function, the numbers 5 and 7 are assigned to the parameters no1 and no2 respectively. If you run the code in terminal the result printed on the screen will be “12”.

So, as you can see, a function can receive values. A function can also return values to print on the screen or assign them to a variable to be manipulated later.

To return a value you have to use the return keyword followed by the expression or variable that you want to return a value. When the return keyword is encountered the execution of the function ends.

Let’s modify the function addition_func to see the return keyword in action.

def addition_func(no1,no2):
	x = no1 + no2
	return(x)
	
x = addition_func(5,7)
print(x)

If you run the code in terminal the output on the screen will be “12”, as in the first example.

Leave a Reply