Table of Contents[Hide][Show]
Functions
So far, we have been writing all our code in the app.py, but as our programs grow, we need a better way to organize our code. We need to break up our code into smaller, more manageable, and more maintainable chunks which we call functions. The function is a container for a few lines of code that perform a specific task.
For example, you have already learned about a few built-in functions in Python print()
and input()
. Each function has a purpose and knows how to perform a specific task. So, when we build large complex programs, we should break up our code into smaller reusable chunks, i.e. functions.
Let us understand this concept by building a program for printing a greeting message.
print('Hi there!')
print('Welcome aboard!')
Here we have a simple program with only two lines of code. Now, let’s say, we’re going to need them in other programs to put them in a function that we can reuse.
Let me introduce a reserved keyword def
in Python, which is short for define and is used for defining a function.
def greet_user():
print('Hi there!')
print('Welcome aboard!')
Now this block of code will define a function “greet_user
” with the lines of codes after that. Whenever this function is called, these two lines will be executed. Let’s use this:
print('start')
greet_user()
print('finish')
The program is executed sequentially, meaning you would have to define a function before calling it in the program.
Parameters
The defined functions work a little bit differently than the built-in functions of Python. For example, in the case of print()
a function, it takes some information that we want to print, but our greet function doesn’t take any information. Wouldn’t it be nicer if you could pass the name of the user here and then, instead of saying “hi there”, you could print the name of the user?
You can do this by adding the parameters inside the parenthesis of the defined function. Let me show you:
def greet_user(name):
print('Hi there!')
print('Welcome aboard!')
Now the “name
” inside the parenthesis will act like a local variable and we can pass the user’s name when calling it.
greet_user('Shahbaz')
Now the name parameter is set to “Shahbaz
”. Let’s alter the program to make use of it.
def greet_user(name):
print(f'Hi {name}')
print('Welcome aboard!')
print('start')
greet_user('Shahbaz')
print('finish')
An important thing to note is that the “name” in the first line is called a Parameter whereas the name supplied i.e. Shahbaz is called an argument.
Let’s go ahead and run this program.
So with these parameters, we can receive information in our functions.
Now, let’s do something interesting. Let’s say you want to add another name to the greeting message. It’s simple.
def greet_user(name):
print(f'Hi {name}')
print('Welcome aboard!')
print('start')
greet_user('Shahbaz')
greet_user('Aayush')
print('finish')
Now note that when a function has a parameter, we are obligated to pass a value for that parameter. If you remove the name from the function and run the program, we will get an error. You can also use multiple parameters in a single function, separated by a comma.
For example, greet_user(first_name, last_name):
. Arguments will also be formatted similarly.
Keyword Arguments
So far, we have learned that whenever we define parameters for our functions we should always supply values otherwise we’ll get an error. In the last program, the arguments 'Shahbaz'
and 'Bhatti'
are called positional arguments, meaning their position or order matters in the program.
In Python, we have another kind of argument called keyword arguments, for which the position doesn’t matter. Let me show you how they work.
Look at the last program. We can modify it like this:
def greet_user(first_name, last_name):
print(f'Hi {first_name} {last_name}')
print('Welcome aboard!')
print('start')
greet_user(first_name='Shahbaz', last_name='Bhatti')
print('finish')
Now the first_name
and last_name
are the keyword parameters. You can switch their places and the result will be the same.
Now that doesn’t mean we should always use keyword arguments. Most of the time we use positional arguments, but in certain situations, these keyword arguments help us improve the readability of our code.
There is one more thing you need to know about keyword arguments. The keyword arguments should always come after positional arguments.
Return Statement
So far we have learned how to create functions and send them information using their parameters. Now let’s learn how to create functions that return values. This is particularly useful if you’re doing some kind of calculations and you want to return the result to whoever is using your function. Let me show you.
Let’s define a function which will calculate the square of a number.
def square(number):
return number*number
We have used the return statement to return this number outside of the function. Now, if we call this function, it returns a value just like the input()
function. Let’s print it on the terminal.
You can argue that the same result can be obtained without using the return statement. Let’s check it out.
We see two things, the number 9, and none. What is happening here?
When the Python interpreter executes this code, first it will call the square function and the control moves to the function. Here we calculate the square of this given number and then print it on the terminal.
Now, by default, all functions return the value none. So if we don’t have a return statement here, by default Python returns none. None is an object that represents the absence of a value. It’s like nothing or null in C, C++, Java and Javascript.
Wrap Up!
I hope you have understood the importance of functions.
They are a significant aspect of Python learning if you are planning to write large and complex programs during your coding career.
Leave a Reply