15Functions and Classes

In this chapter, we are going to introduce the concepts of functions and classes and how these concepts can be introduced into the way you code in Python. Thus far in this book everything has been shown as blocks of code. These blocks of code may be just snippets to demonstrate a specific concept or longer sections to demonstrate how to perform a task. When you come to practically write your code you can write it in the manner that you have seen within this book and that is perfectly acceptable. However, if you want to group code together or reuse it then functions and classes are a great thing to use.

Let's start with functions, these are very useful for code that you want to reuse or if you have repeated code, then a function can help you. Functions also allow you to run code with arguments which gives you the ability to have the behaviour of the function dictated by the variables you pass to it. Let's demonstrate how to setup a function by using the lottery example from before. Now to familiarise ourselves with the code we looked to generate the results of a lottery draw using elements of code that we had used up to that point of the book. The results look as follows:

image

Now, we can cast this a function called lottery as follows:

image

What we have done ...

Get The Python Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.