Python Tutorial #6 - Functions
Hello everyone and welcome back to the Python Tutorial! Today we're gonna take a look at functions.
Functions
Functions are little pieces of code that we can write to be executed on a later point under a certain condition.
They're also supposed to reduce the amount of code you have to write because they prevent you from writing multiple lines of code with the same content. Let's look at a little example.
def function():
print("This is a function test!")
As you execute this code, you will see that ...well... nothing happens. This is because python stored this piece of code for you instead of executing it. You can use it anywhere on a later point like this:
def function():
print("This is a function test!")
function()
Never forget the brackets on a function definition or call because this will lead to the function not being recognised as such.
If we execute this, the code will work as expected and gives us This is a function test!
as Output.
If we used Functions only like this, the only use would be avoiding the typing of our function code multiple times. But of course there is more we can do with it. What about a function that executes a simple operation for us?
def add(parameter1, parameter2):
result = parameter1 + parameter2
return result
value = add(5, 2)
print("value")
This will give us the Output 7, since 5 + 2 equals 7. But how does this work? Well, we can pass so called parameters to a function. If we want to do this, we have to declare every parameter we will pass in the function definition. We can do this by writing them in the brackets behind the function name, seperated with commas.
We can refer to those parameters inside of the function by using the name we gave them in the declaration. The return
statement finally returns our result to the main code.
The
print()
statement itself is also a function which takes your input and prints it on the screen.
If we want to call this function, we have to give the parameters to her by writing them in the brackets behind the call. Those parameters can of course also be variables which we declared earlier.
For every function which returns a output, we need to pipe that output into a variable for further use, or it's lost. We can do this like this: a = function()
, in which a is the variable name.
That's all! I hope you enjoyed todays Tutorial. In the next part we will write our own little calculator to test the knowledge we've acquired so far. If you have any Questions, write them in the commentaries!
This post received a free Upvote. Get your free Upvote NOW! Just follow @freeupvote