Creating functions in Python

I am going to tell you some more about creating functions in Python in this blog. In the blog about calling functions of last week I already explained a little bit about making your own functions. In this blog I am coming back on that subject. User-defined functions are really nice to use, because you only need to define the function ones. After that you can easily use them on different spots in your script, without the need to write it again. That can also result in a better overview of your code. To use user-defined functions can also be very practic when you are doing assignments in groups. Everybody can write an own user defined function in different files. In that way you can work with the whole group at the same time on a code.

So to create your own function, you first need to make a function. In this blog I am going to use the function again that I created for WSQ02. So the name of this file is also WSQ02. To use this as a function in a new file, you only need to import it:

In this video you can see how I imported it.

There is also a totally different way to define your own functions. You need to define those functions in your own script. So first you start the line with ‘def’ (from define). After that you need to put a space and type the name that you want to assign to the function. For example if the functions is about cookies, you can fill up the line with that and you get ‘def cookies’. After that you need to make the input for your function between brackets and end with a colon. So for example, you can have three different input and the function becomes: ‘def cookies(quantity, shape, ingrediënt):’. After you defined your function you have the print it in the same way, so you get: ‘print(quantity, shape, ingrediënt)’. After that you can define the input of your function: ‘cookies(quantity=’5′, shape=’round’, ingrediënt=’chocolate’). If your run it will give you 5 round chocolate:

Because of the fact that you defined this function in your script and not only use it, it is possible to wright some code and after that use your cookies functions again:

So in this blog I described some more about user defined functions, calling them and using them. I hope you enjoyed it, understand it and learned a couple of new things!

Plaats een reactie

Ontwerp een vergelijkbare site met WordPress.com
Aan de slag