Now is the time to start working with functions. A
function is a reusable block of code that you can
reuse later in your program as many times as you
want. So why do you need functions? Well, this
will help you create building blocks in your
program that you can use and reuse on top of each
other, so you can increase the complexity of the
application, without increasing the complexity of
your code. Your code will stay clean, and easy to
modify. And instead of giving you many theoretical
explanations, let's dive in and write our first
function. Okay, I'm going to remove all of that,
I'm going to create a function. So to write a
function, you first need to write the def, def and
then space, and then the name of the function.
Let's say we want to function that says hello. So
I'm going to write say_hello. That is the name of
the function. After the name of the function, you
need to open and close parentheses, and then add a
colon. After this, you can press enter, and as
you can see, the marker here doesn't, the cursor
doesn't come back to here. It come back to here
with, as you can see here, 1234 new spaces, which
is called the indentation, okay. So you're going
to write everything under this function with an
indentation of four spaces. So I can write any
instruction I want. So for example, print("Hello").
Okay, that's a very basic function that just says
Hello. So def,name of the function. So again,
what you can do, if you want to add multiple
words, you can add an underscore, and then parenthesis colon,
and everything you write inside the
function will be with an indentation. Now, if I
run that code, let's run the main, you can see,
well, we have nothing. Why is that? Because we
have just created a function, okay, we didn't call
the function, okay. If you just create, if you
just define a function like this, it is not going to
do anything. What you need to do in your code is
to call the function, and to call the function, you
just write the name of the function, okay, with
the parentheses. And then you can run the
again, and you can see Hello. So the good thing
about a function is that you can actually call it
multiple times. So I can just copy this and paste
it three times. And it's going to call the
function three times. You can see Hello, Hello,
Hello. So of course, make sure you define the
function before you call it okay, otherwise,
you're going to get an error. And then as you can
see here, everything that is indented will be
under the function. So let's say I write print,
let's say I write test, okay. I can run again and you can
see Hello, test, Hello, test, Hello, test. So if I
continue to add lines after this one, but with an
indentation of four spaces, it's going to be under
the function. When I go back to the default
indentation of zero spaces, we are back to the
main program and then so we can call the function
directly like this.