#7: Functions
I spent this week consolidating all the things I learned so far of Python. I rewatched a few topics on Pluralsight to fill in gaps I noticed while writing the drafts of the next few posts. That is another positive benefit of trying to blog every week about your progress on learning a new programming language.
Functions
Functions help us to organise and reuse code to perform a specific action. While we can write that code over and over again, it is much simpler to create a function once and then call it from wherever we need it.
We can define a function using the def keyword followed by the name of our function, a pair of () and a colon:
To execute or function, we can call it like this:
We can use parameters to make our function more flexible. The parameters go between the () and need a name:
We can now execute our function by giving it an argument that will influence what our function returns:
A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. (as explained on Stack Overflow by Torbjörn Hansson and Patrick Brinich-Langlois)
Default parameters
Sometimes our functions have a good default value. Instead of using this value as an argument with every call, we can modify our function definition to include it. After the parameter name you just need to write a = and that value:
If we now call our function without an argument, the default value is used:
If we call our function with an argument, then our value is used instead of the default one:
This gives us a lot of flexibility and is a great help when we need to refactor our code.
Multiple parameters
Functions can have multiple parameters. We just need to make sure that we give all of them a unique name:
We can call this function using the same order for our arguments as the function definition uses (called positional arguments):
If we want, we can use the parameter name in front and get the same result:
That looks like a lot more work. However, by using the parameter name we are able to change the order in which we write our arguments:
This form is especially helpful when there are many parameters with default values and we only need to set a few of them.
Arbitrary number of arguments
Some functions in Python like print let you add as many arguments as you like:
If you want to do the same with your functions, you can use a * in front of your parameter name. Inside your function you can access the parameter without the * and get a tuple of all the values:
Next
Functions only help us when we can put them somewhere that we then can use in our code. Therefore, the next step is to create a module.