What is a function? Well, when we tell the Python interpreter:
we are using the function: print().
A function is something the computer knows how to do. We use functions all the time when we are programming.
It’s useful to create our own functions. If there is a specific thing that we need to do quite often in a program, we can define a function that does it. There are several advantages to this. Firstly, we don’t have to type in the code for this operation every time we need to do something. Secondly, if we need to change something about that action, we only need to change it once, in the definition of the function. Here’s an example.
This function just draws a little square. In a program this simple, there isn’t really an advantage in using a function, but as your programs become more complex, you’ll find them very useful. As you can see, we define the function at the start of the of the program. That way, when the computer comes across our call to that funtion, it will know what to do. To define a function we type: “def function_name():” After this comes an indented block of code which is what the computer will do when we call the function. We call the function by entering: “function_name()”.
Just like with the other functions we have used, we can use the bracketed part of the function call to pass information to the function. Here’s an example:
This time the function is expecting a value – “side”. So if we say “square(50)”, it will draw a square with ides 50 steps long. If we change the “main” part of the program to:
size = int(input(“How long do you want the side to be?”))
the program will ask tell the function to draw a square with lines the length that we specified.
There’s a lot more we can do with function, but hopefully this gives you the basic idea.