A function is a block of organized, reusable code. Functions simplify the coding process, prevent redundant logic, and make the code easier to follow and allow you to use the same code over and over again.
Creating clean, readable and reusable functions is a key part of becoming an effective Python programmer.
In this article, we will walk you through defining and using functions in Python.
Functions In Python
Python comes with a number of inbuilt function which we use pretty often print()
, int()
,float()
, len()
and many more.
Besides built-ins we can also create our own functions to do more specific jobs, these are called user-defined functions
Following is the syntax for creating our own functions in Python,
def name_of_function():
code
A Python function should always start with the def
keyword, which stands for define. Then we have the name of the function (typically should be in lower snake case), followed by a pair of parenthesis() which may hold parameters of the function and a semicolon(:) at the end.
The code inside the function should always be indented because Python relies on indentation to figure out which block of code belongs to the function.
Let's head on to create our first function. We will create a basic function which simply prints "Hello".
def my_func():
print("Hello")
my_func()
We created a function named my_func
, and inside the function, we have the print statement.
In order to run our function, we first need to call it outside the function block, we are calling our function with the function name followed with parenthesis.
The above function gives the following output:
Hello
Parameters in Function
So far we are not passing any additional parameter or arguments to the function, but we can define the parameter in the function definition in the parenthesis.
The parameter is an optional list of identifiers that get bound to the values supplied as arguments when the function is called. A function may have an arbitrary number of arguments which are separated by commas.
Let's create a function which takes parameters.
def my_func(name):
print("Hello " + name)
my_func('Jhon')
This time function is taking the parameter name, and inside the function, we are printing "Hello" along with the name. This name was passed while calling the function below.
Output:
Hello Jhon
So far our functions are only printing strings. However, in real-world programs, we use the return
keyword to return back the result of the function.
The return keyword allows us to store the result of the function in a variable. Unlike many other languages, we do not need to declare a return type of the function explicitly. Python functions can return values of any type via the return keyword.
def add_num(num1, num2):
print(num1 + num2)
add_num(2, 3)
In the above example, we are adding 2 numbers and printing them, but we can't assign the result of the addition to a variable.
You can verify it by storing it in a variable and printing the variable like so:
def add_num(num1, num2):
print(num1 + num2)
result =add_num(2, 3)
print("The result is =",result)
Output:
The result is = None
The return keyword allows us to store the result in a variable, usually almost every time while writing a function you will use the return keyword.
def add_num(num1, num2):
return(num1 + num2)
result =add_num(2, 3)
print(result)
Output:
5
Quick note - using parenthesis in the return keyword is not mandatory.
Keyword Arguments In Functions
In addition to calling parameters in order, you can use keyword arguments in a function call, in which the caller identifies the arguments by the parameter name.
Parameters have positional behavior, and you need to inform them in the same order that they were defined. Keyword arguments allow us to use function parameters in any order we like.
def sub_num(num1, num2):
return num1 - num2
result =sub_num(num1 = 2,num2 = 3)
print(result)
The above function performs subtraction; We passed parameters to the function with keyword arguments num1 and num2 which gave us the output -1.
Keyword arguments allow us to use parameters in any order because the Python interpreter will use the keywords provided to match the values to the parameters.
def sub_num(num1, num2):
return num1 - num2
result =sub_num(num2 = 2,num1 = 3)
print(result)
Here we switched the order of the parameters. As a result, we got output +1.
Default Argument Values
Binding default values to the function parameters is also possible. Let's go back to our previous example.
def my_func(name):
print("Hello " + name)
my_func('Jhon')
Now add a default name "Rick" to the function.
def my_func(name = "Rick"):
print("Hello " + name)
my_func()
This will give output "Hello Rick", when fthe unction call has no paramters.
However, we can still pass parameters in the function call which will overwrite the default parameter.
def my_func(name = "Rick"):
print("Hello " + name)
my_func('Jhon')
Output:
Hello Jhon
A function can have conditional statements and loops, now that we know the basics of a function let's construct an advanced function.
This function generates a secret code for our input, this function converts all the vowels of the provided string into "x."
def secret_code_gen(string):
output = list(string)
for i, letter in enumerate(string):
for vowel in ['a', 'e', 'i', 'o', 'u']:
if letter.lower() == vowel:
output[i] = 'x'
output = ''.join(output)
return output
result = secret_code_gen("This is my secret code")
print(result)
Output:
Thxs xs my sxcrxt cxdx
In the above function, first, we are taking a string and converting it to list of characters. Then we are iterating over the list characters replacing all the vowels of the string with the letter X and finally joining them into a single string object.